import { Injectable, Logger, Scope, OnModuleInit } from '@nestjs/common'; import mongoose from 'mongoose'; import { applyMongoosePerformancePlugin } from '../observability/mongoose-performance.plugin'; import { SecretService } from '../secret/secret.service'; import { tournamentModelDefinitions, TournamentModelTypes } from './schema'; export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string { if (nodeEnv === 'prod') return 'lolympus'; if (nodeEnv === 'staging') return 'lolympus-staging'; return 'lolympus-dev'; } export function resolveMongoAppName( nodeEnv = process.env.NODE_ENV, pid = process.pid, ): string { return `lolympus-api:${nodeEnv || 'dev'}:${pid}`; } export function resolveMongoConnectionOptions( dbName: string, appName: string, mongoAutoIndex = process.env.MONGODB_AUTO_INDEX, ): mongoose.ConnectOptions { const shouldEnableMongoAutoIndex = mongoAutoIndex?.trim().toLowerCase() === 'true'; return { dbName, appName, minPoolSize: 10, maxPoolSize: 20, autoIndex: shouldEnableMongoAutoIndex, autoCreate: false, }; } @Injectable({ scope: Scope.DEFAULT }) export class ConnectionService implements OnModuleInit { private readonly logger = new Logger(ConnectionService.name); private connection: mongoose.Connection | null = null; private connectionPromise: Promise | null = null; constructor(private readonly secretService: SecretService) {} private tournamentModels: Map> | null = null; public async getConnection(): Promise { if ( this.connection !== null && this.connection.readyState === mongoose.ConnectionStates.connected ) { return this.connection; } const pendingConnection = this.connectionPromise ?? this.openConnection(); this.connectionPromise = pendingConnection; try { return await pendingConnection; } finally { if (this.connectionPromise === pendingConnection) { this.connectionPromise = null; } } } private async openConnection(): Promise { const connectionString = await this.secretService.get( 'MONGODB_CONNECTION_STRING', ); const dbName = resolveMongoDbName(); const appName = resolveMongoAppName(); const connectionOptions = resolveMongoConnectionOptions(dbName, appName); const connection = await mongoose .createConnection(connectionString, connectionOptions) .asPromise(); this.connection = connection; this.tournamentModels = null; this.logger.log( `MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${ connectionOptions.autoIndex === true }`, ); return connection; } public async getModel( modelKey: K, ): Promise> { const connection = await this.getConnection(); if (this.tournamentModels) return this.tournamentModels.get(modelKey) as mongoose.Model< TournamentModelTypes[K] >; const models = new Map>(); tournamentModelDefinitions.forEach((modelDefinition) => { applyMongoosePerformancePlugin(modelDefinition.schema); // 이미 생성된 경우 컴파일 스킵. if ( Object.prototype.hasOwnProperty.call( connection.models, modelDefinition.name, ) ) { models.set( modelDefinition.name as K, connection.models[modelDefinition.name], ); return; } else { models.set( modelDefinition.name as K, connection.model( modelDefinition.name, modelDefinition.schema, modelDefinition.schemaName, ), ); } }); this.tournamentModels = models; return models.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) { this.logError('Failed to start MongoDB session', error); } } public async onModuleInit() { await this.getConnection().catch((error: unknown) => { this.logError('Failed to initialize MongoDB connection', error); }); } public async onModuleDestroy() { await this.connection?.close(); } private logError(message: string, error: unknown): void { this.logger.error( `${message}: ${error instanceof Error ? error.message : String(error)}`, error instanceof Error ? error.stack : undefined, ); } }