Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

216
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda