import { Injectable, Scope, OnModuleInit } from '@nestjs/common'; import mongoose from 'mongoose'; import { SecretService } from '../secret/secret.service'; import { moeumModelDefinitions, MoeumModelTypes } from './schema'; @Injectable({ scope: Scope.DEFAULT }) export class ConnectionService implements OnModuleInit { private connection: mongoose.Connection | null = null; constructor(private readonly secretService: SecretService) {} private moeumModels: Map> | null = null; public async getConnection(): Promise { if (this.connection !== null && this.connection.readyState === 1) { return this.connection; } const connectionString = await this.secretService.get( 'MONGODB_CONNECTION_STRING', ); const defaultConnection = await mongoose .createConnection(connectionString, { dbName: 'moeum', minPoolSize: 10, maxPoolSize: 20, }) .asPromise(); this.connection = defaultConnection; console.log('Default Connection이 새로 생성됨.'); return this.connection; } public async getMoeumModels( modelKey: K, ): Promise> { if (this.moeumModels) return this.moeumModels.get(modelKey) as mongoose.Model< MoeumModelTypes[K] >; const moeumModels = new Map>(); // const connection = await this.getTenantConnection(tenantId); const connection = await this.getConnection(); moeumModelDefinitions.forEach((modelDefinition) => { // 이미 생성된 경우 컴파일 스킵. if ( Object.prototype.hasOwnProperty.call( connection.models, modelDefinition.name, ) ) { moeumModels.set( modelDefinition.name as K, connection.models[modelDefinition.name], ); return; } else { moeumModels.set( modelDefinition.name as K, connection.model( modelDefinition.name, modelDefinition.schema, modelDefinition.schemaName, ), ); } }); this.moeumModels = moeumModels; return moeumModels.get(modelKey) as mongoose.Model; } public async createSession( options?: mongoose.ClientSessionOptions, ): Promise { try { const connection = await this.getConnection(); const session = await connection.startSession(options); return session as unknown as mongoose.ClientSession; } catch (error) { console.log(error); } } public async onModuleInit() { await this.getConnection().catch(console.error); } public async onModuleDestroy() { this.connection?.close(); } }