Ask Your Question

Revision history [back]

click to hide/show revision 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) {}
}
  1. Create a function that takes in the new configuration and sets the new connection on the sequelize instance
  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();
  }
  1. Call the setDbConnection function with the new configuration
  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.