feat(api): add database connection
This commit is contained in:
1 parent
7cde555bef
commit
714349d519
4 files changed
+128
No files matched your search
@@ -0,0 +1,14 @@
|
||||
import { resolveMongoDbName } from './connection.service';
|
||||
|
||||
describe('resolveMongoDbName', () => {
|
||||
it('uses production database only for prod', () => {
|
||||
expect(resolveMongoDbName('prod')).toBe('lolympus');
|
||||
});
|
||||
|
||||
it('uses isolated databases for non-production environments', () => {
|
||||
expect(resolveMongoDbName('dev')).toBe('lolympus-dev');
|
||||
expect(resolveMongoDbName('test')).toBe('lolympus-test');
|
||||
expect(resolveMongoDbName('')).toBe('lolympus-dev');
|
||||
expect(resolveMongoDbName('local')).toBe('lolympus-dev');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Injectable, Scope, OnModuleInit } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
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 === 'test') return 'lolympus-test';
|
||||
return 'lolympus-dev';
|
||||
}
|
||||
|
||||
@Injectable({ scope: Scope.DEFAULT })
|
||||
export class ConnectionService implements OnModuleInit {
|
||||
private connection: mongoose.Connection | null = null;
|
||||
constructor(private readonly secretService: SecretService) {}
|
||||
|
||||
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
||||
|
||||
public async getConnection(): Promise<mongoose.Connection> {
|
||||
if (this.connection !== null && this.connection.readyState === 1) {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
const connectionString = await this.secretService.get(
|
||||
'MONGODB_CONNECTION_STRING',
|
||||
);
|
||||
const dbName = resolveMongoDbName();
|
||||
const defaultConnection = await mongoose
|
||||
.createConnection(connectionString, {
|
||||
dbName,
|
||||
minPoolSize: 10,
|
||||
maxPoolSize: 20,
|
||||
})
|
||||
.asPromise();
|
||||
this.connection = defaultConnection;
|
||||
console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`);
|
||||
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
public async getModel<K extends keyof TournamentModelTypes>(
|
||||
modelKey: K,
|
||||
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
||||
if (this.tournamentModels)
|
||||
return this.tournamentModels.get(modelKey) as mongoose.Model<
|
||||
TournamentModelTypes[K]
|
||||
>;
|
||||
|
||||
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
|
||||
const connection = await this.getConnection();
|
||||
|
||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||
// 이미 생성된 경우 컴파일 스킵.
|
||||
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<TournamentModelTypes[K]>(
|
||||
modelDefinition.name,
|
||||
modelDefinition.schema,
|
||||
modelDefinition.schemaName,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
this.tournamentModels = models;
|
||||
return models.get(modelKey) 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) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async onModuleInit() {
|
||||
await this.getConnection().catch(console.error);
|
||||
}
|
||||
|
||||
public async onModuleDestroy() {
|
||||
this.connection?.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { DynamicModule, Module } from '@nestjs/common';
|
||||
import { ConnectionService } from './connection.service';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
providers: [ConnectionService],
|
||||
exports: [ConnectionService],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,5 @@
|
||||
export interface ModelDefinition {
|
||||
name: string;
|
||||
schema: mongoose.Schema<any>;
|
||||
schemaName?: string;
|
||||
}
|
||||
Reference in new issue
Block a user