1 | initial version |
To change the database connection within an interceptor in NestJS using Sequelize-Typescript, you can do the following:
app.module.ts
file, each with a different database connection:@Module({
imports: [
SequelizeModule.forRoot({
...
config: {
database: 'db1',
...
},
}),
SequelizeModule.forRoot({
...
config: {
database: 'db2',
...
},
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
SequelizeService
into your interceptor:import { Injectable, NestInterceptor, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
import { SequelizeService } from '@nestjs/sequelize';
@Injectable()
export class MyInterceptor implements NestInterceptor {
constructor(private sequelizeService: SequelizeService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
// Change the Sequelize's default connection to another database
this.sequelizeService.set('db2');
// Execute the route handler
return next.handle();
}
}
set()
method of the SequelizeService
to switch to the desired database connection.Now, when your interceptor is executed, the Sequelize instance will use the db2
connection instead of the default db1
connection.