1 | initial version |
To dynamically change the database connection in NestJS Sequelize, you can follow these steps: 1. Inject the Sequelize instance from the sequelize module in your service or controller
import { Sequelize } from 'sequelize-typescript';
import { Inject } from '@nestjs/common';
@Injectable()
export class MyService {
constructor(@Inject(Sequelize) private readonly sequelize: Sequelize) {}
}
setDbConnection(config: any): void {
this.sequelize.close(); // close the previous connection
this.sequelize.config.database = config.database;
this.sequelize.config.username = config.username;
this.sequelize.config.password = config.password;
this.sequelize.config.host = config.host;
this.sequelize.config.port = config.port;
this.sequelize.config.dialect = config.dialect;
this.sequelize.config.logging = config.logging;
this.sequelize.authenticate();
}
const newDbConfig = {
database: 'new-db',
username: 'admin',
password: 'admin',
host: 'localhost',
port: 3306,
dialect: 'mysql',
logging: false
};
this.setDbConnection(newDbConfig);
Note that this example assumes you are using sequelize-typescript and have already configured your Sequelize instance with the database connection information.