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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-05-19 11:00:00 +0000
Seen: 9 times
Last updated: Dec 28 '21
Is it possible to launch multiple instances of PostgreSQL using Spring Boot Testcontainers?
How to eliminate null values when grouping data in DB2?
What does the DB2 Trigger do following an insertion?
How can I link to two distinct MongoDB databases in my Nuxt 3/ Vue 3 application?
What does @mock_dynamodb2 do with table context?
What is the driver for DB2 that uses the R2DBC protocol?
How can SQLAlchemy be used to establish a connection with an IBM DB2 database?