import { Connection, Driver, getConnection } from 'typeorm'; import { BaseConnectionOptions } from 'typeorm/connection/BaseConnectionOptions'; import { AppLogger } from '../logger/logger'; export class TypeOrmConnectionManagerService { private static readonly TAG: string = `${TypeOrmConnectionManagerService.constructor.name}`; static reconnectionPromise: Promise = null; static isConnection: boolean = false; static async reconnectDriverToDb(connectionName: string, username: string, password: string): Promise { TypeOrmConnectionManagerService.isConnection = true; TypeOrmConnectionManagerService.reconnectionPromise = new Promise(async (resolve, reject) => { try { AppLogger.debug('Try to reconnected driver to the DB', TypeOrmConnectionManagerService.TAG); const connectionPool: Connection = getConnection(connectionName); const driver: Driver = connectionPool.driver; await driver.disconnect(); const oldDriverOptions: BaseConnectionOptions = driver.options; driver.options = { ...oldDriverOptions, username, password, } as BaseConnectionOptions; await driver.connect(); AppLogger.debug('Driver reconnected successfully', TypeOrmConnectionManagerService.TAG); resolve(null); } catch (e) { AppLogger.error(e, TypeOrmConnectionManagerService.TAG); reject(); } finally { TypeOrmConnectionManagerService.isConnection = false; } }); } }