Search code examples
nestjstypeorm

typeorm 0.3.6 - db connection per request


I’m migrating from 0.2.* to 0.3.6 version of typeorm. I’m not sure how to handle multi-tenant connections with new DataSource. My previous implementations was based on connectionManager and it looked something like this:

{
    const connectionManager = getConnectionManager();

    // Check if tenant connection exists
    if (connectionManager.has(tenant.name)) {
      const connection = connectionManager.get(tenant.name);
      return Promise.resolve(
        connection.isConnected ? connection : connection.connect()
      );
    }

    // Create new tenant connection
    return createConnection({
      type: 'postgres',
      name: tenant.name,
      host: tenant.host,
      port: tenant.port,
      username: tenant.username,
      password: tenant.password,
      database: tenant.database,
      entities: [...TenantModule.entities],
    });
}

Connection manger is now deprecated. Maintaining my own array of connections doesn’t sound right to me. Any ideas on how this should be handled the correct way?


Solution

  • with typeorm: 0.3.6 getConnection, createConnection among others are deprecated. You can find migration guide in here

    to create a new connection, you will have to use DataSource as follows:

    import { DataSource, DataSourceOptions } from 'typeorm';
    
    const dataSourceOptions: DataSourceOptions = {
      type: 'mysql',
      host,
      port,
      username,
      password,
      database,
      synchronize: false,
      logging: false,
      entities: ['src/database/entity/*.ts'],
      migrations: ['src/database/migration/*.ts'],
    };
    
    export const AppDataSource = new DataSource(dataSourceOptions);
    

    where new DataSource is equivalent to new Connection and dataSource is equal to getConnection.

    To check if you are connection to database, you will have utilize AppDataSource:

    AppDataSource.initialize()
      .then(() => {
        // db initialized
      })
      .catch((err: Error) => {
        throw new Error(`'Database connection error: ${err}`);
      });