Files
lolympus-tournament-support/apps/api/src/modules/global/database/connection.service.ts
T

177 lines
5.3 KiB
TypeScript

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,
type 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<mongoose.Connection> | null = null;
constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<keyof TournamentModelTypes, unknown> | null =
null;
public async getConnection(): Promise<mongoose.Connection> {
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<mongoose.Connection> {
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<K extends keyof TournamentModelTypes>(
modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
const connection = await this.getConnection();
if (this.tournamentModels) {
return this.requireTournamentModel(this.tournamentModels, modelKey);
}
const models = new Map<keyof TournamentModelTypes, unknown>();
tournamentModelDefinitions.forEach((modelDefinition) => {
if (!(modelDefinition.schema instanceof mongoose.Schema)) {
throw new Error(
`Invalid Mongoose schema for model ${modelDefinition.name}.`,
);
}
applyMongoosePerformancePlugin(modelDefinition.schema);
// 이미 생성된 경우 컴파일 스킵.
if (
Object.prototype.hasOwnProperty.call(
connection.models,
modelDefinition.name,
)
) {
models.set(
modelDefinition.name,
connection.models[modelDefinition.name],
);
return;
} else {
models.set(
modelDefinition.name,
connection.model(
modelDefinition.name,
modelDefinition.schema,
modelDefinition.schemaName,
),
);
}
});
this.tournamentModels = models;
return this.requireTournamentModel(models, modelKey);
}
private requireTournamentModel<K extends keyof TournamentModelTypes>(
models: ReadonlyMap<keyof TournamentModelTypes, unknown>,
modelKey: K,
): mongoose.Model<TournamentModelTypes[K]> {
const model = models.get(modelKey);
if (model === undefined) {
throw new Error(`Mongoose model ${modelKey} is not registered.`);
}
return model as mongoose.Model<TournamentModelTypes[K]>;
}
public async createSession(
options?: mongoose.ClientSessionOptions,
): Promise<mongoose.ClientSession | undefined> {
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,
);
}
}