|
| 1 | +import { getConnectionManager, DataSource } from 'typeorm'; |
| 2 | +import { SnakeNamingStrategy } from 'typeorm-naming-strategies'; |
| 3 | +import { LoggerService } from '../logger/logger.service'; |
| 4 | +import { ExecutionManager } from './execution.manager'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Get connection based on the logged in tenant |
| 8 | + * @returns connection |
| 9 | + */ |
| 10 | + |
| 11 | +export async function getConnection(): Promise<DataSource> { |
| 12 | + const tenantName = ExecutionManager.getTenantId(); |
| 13 | + return getConnectionForTenant(tenantName); |
| 14 | +} |
| 15 | + |
| 16 | +export async function getConnectionForTenant( |
| 17 | + tenantId: string, |
| 18 | +): Promise<DataSource> { |
| 19 | + if (getConnectionManager().has(tenantId)) { |
| 20 | + const con = getConnectionManager().get(tenantId); |
| 21 | + const existingConnection = await Promise.resolve( |
| 22 | + con.isConnected ? con : con.connect(), |
| 23 | + ); |
| 24 | + await switchToTenant(tenantId, existingConnection); |
| 25 | + |
| 26 | + return existingConnection; |
| 27 | + } |
| 28 | + |
| 29 | + const newConnection: DataSource = await new DataSource({ |
| 30 | + name: tenantId, |
| 31 | + type: 'postgres', |
| 32 | + host: process.env.POSTGRES_HOST, |
| 33 | + port: Number(process.env.POSTGRES_PORT), |
| 34 | + username: process.env.POSTGRES_USER, |
| 35 | + password: process.env.POSTGRES_PASSWORD, |
| 36 | + database: process.env.POSTGRES_DB, |
| 37 | + entities: [ |
| 38 | + __dirname + '/../**/*.entity.ts', |
| 39 | + __dirname + '/../**/*.entity.js', |
| 40 | + ], |
| 41 | + synchronize: false, |
| 42 | + logging: ['error'], |
| 43 | + namingStrategy: new SnakeNamingStrategy(), |
| 44 | + extra: { max: process.env.POSTGRES_TENANT_MAX_CONNECTION_LIMIT }, |
| 45 | + }).initialize(); |
| 46 | + |
| 47 | + await switchToTenant(tenantId, newConnection); |
| 48 | + |
| 49 | + return newConnection; |
| 50 | +} |
| 51 | + |
| 52 | +const switchToTenant = async ( |
| 53 | + tenantId: string, |
| 54 | + connection: DataSource, |
| 55 | +): Promise<void> => { |
| 56 | + try { |
| 57 | + await connection.query(`select set_config('app.tenant_id', $1, false)`, [ |
| 58 | + tenantId, |
| 59 | + ]); |
| 60 | + } catch (error) { |
| 61 | + const logger = LoggerService.getInstance('bootstrap()'); |
| 62 | + logger.error( |
| 63 | + `Failed to switch to tenant: ${tenantId}, error: ${JSON.stringify( |
| 64 | + error, |
| 65 | + )}]`, |
| 66 | + ); |
| 67 | + } |
| 68 | +}; |
0 commit comments