In order to allow multi tenancy I'm creating request scoped instances of Sequelize depending on a tenant's subdomain, e.g. team1.example.com creates an instance accessing database schema "team1". Researching this topic lead me to the example of async configuration for Sequelize using a config service, which looks like this:
import { Inject, Injectable, Scope, Request } from "@nestjs/common";
import { REQUEST } from "@nestjs/core";
import { SequelizeModuleOptions, SequelizeOptionsFactory} from "@nestjs/sequelize";
@Injectable({scope:Scope.REQUEST})
export class SequelizeConfigService implements SequelizeOptionsFactory {
constructor(@Inject(REQUEST) private readonly request:Request){}
createSequelizeOptions(): SequelizeModuleOptions {
let domain:string[]
let database='default'
domain=this.request['headers']['host'].split('.')
if(domain[0]!='localhost' && domain[0]!='127' && domain[0]!='www' && domain.length >2){
database=domain[0]
}
return {
dialect: 'mysql',
host: 'localhost',
port: 3306,
username: 'localuser',
password: 'supersecretpassword',
database: database,
autoLoadModels: true,
synchronize: true,
};
}
}
The configuration is then used when importing Sequelize in a module:
@Module({
imports: [
SequelizeModule.forRootAsync({
useClass:SequelizeConfigService
}),
SequelizeModule.forFeature([User])
],
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
This works fine but this mechanism creates a new instance (and thus a connection) with every request which will lead to performance issues eventually.
Is there a way to store Sequelize instances / connections which have already been created for a tenant to re-use them for subsequent requests?