Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Use dynamically created Sequelize Instance in NestJS

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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda