Search code examples
javascriptnestjstypeorm

TypeORM NestJS migration form 0.2 to 0.3 multi tenant schema


I want to upgrade typeorm to version 3 but I am left with the problem of linking to the correct schema, my file looks like this:

import {
    Connection,
    createConnection,
    getConnectionManager,
} from 'typeorm';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions';

import * as tenantsOrmconfig from '../../tenants-orm.config';

export function getTenantConnection(tenantId: string): Promise<Connection> {
    const connectionName = `tenant_${tenantId}`;
    const connectionManager = getConnectionManager();

    if (connectionManager.has(connectionName)) {
        const connection = connectionManager.get(connectionName);
        return Promise.resolve(connection.isConnected ? connection : connection.connect());
    }

    return createConnection({
        ...(tenantsOrmconfig as PostgresConnectionOptions),
        name: connectionName,
        schema: connectionName,
    });
}

I have to replace getConnectionManager, do You have any idea ?


Solution

  • you can walk around my repo, i've a function like this to create connection:

    async createConnection(name: string) {
        const config = await this.getDatabaseConfig(name); //this is just get config by name in my db
        if (!config) {
          throw new BadRequestException('DATABASE NOT FOUND');
        }
        config.password = this.decryptPassword(config.password);
        const configs = {
          ...config,
          entities: ['dist/**/*.entity.{ts,js}'],
          migrations: ['dist/migrations/*.{ts,js}'],
          migrationsRun: true,
          migrationsTableName: 'typeorm_migrations',
          synchronize: false,
          ssl: false,
          logging: true,
        } as DataSourceOptions;
        const connection = new DataSource(configs);
        if (!connection.isInitialized) await connection.initialize();
        console.log('isInitialized', connection.isInitialized);
        return connection;
      }
    
    

    and use like this:

    const connection: DataSource = await this.dynamicDbService.createConnection(
      name,
    );