Ask Your Question
2

How can I change the database connection within an interceptor in NestJS using Sequelize-Typescript?

asked 2022-05-19 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-12-28 16:00:00 +0000

woof gravatar image

To change the database connection within an interceptor in NestJS using Sequelize-Typescript, you can do the following:

  1. Define multiple Sequelize configurations in your 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 {}
  1. Inject the 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();
  }
}
  1. Call the 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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-05-19 11:00:00 +0000

Seen: 9 times

Last updated: Dec 28 '21