diff --git a/apps/api/src/modules/global/database/connection.service.spec.ts b/apps/api/src/modules/global/database/connection.service.spec.ts index 656be2c..168ccfd 100644 --- a/apps/api/src/modules/global/database/connection.service.spec.ts +++ b/apps/api/src/modules/global/database/connection.service.spec.ts @@ -1,8 +1,10 @@ import { + ConnectionService, resolveMongoAppName, resolveMongoConnectionOptions, resolveMongoDbName, } from './connection.service'; +import { modelDefinitions } from './schemas'; describe('resolveMongoDbName', () => { it('uses production database only for prod', () => { @@ -17,6 +19,57 @@ describe('resolveMongoDbName', () => { }); }); +describe('ConnectionService.ensureCollections', () => { + function createConnectionService() { + return new ConnectionService({ + get: jest.fn(), + ready: jest.fn(), + } as never); + } + + it('creates every registered collection that does not exist yet', async () => { + const connectionService = createConnectionService(); + const hasNext = jest.fn().mockResolvedValue(false); + const listCollections = jest.fn(() => ({ hasNext })); + const createCollection = jest.fn().mockResolvedValue(undefined); + const getModel = jest.fn().mockResolvedValue({ createCollection }); + + connectionService.getConnection = jest.fn().mockResolvedValue({ + db: { listCollections }, + }); + connectionService.getModel = getModel; + + await connectionService.ensureCollections(); + + expect(listCollections).toHaveBeenCalledTimes(modelDefinitions.length); + expect(listCollections).toHaveBeenCalledWith( + { name: 'account' }, + { nameOnly: true }, + ); + expect(getModel).toHaveBeenCalledTimes(modelDefinitions.length); + expect(createCollection).toHaveBeenCalledTimes(modelDefinitions.length); + }); + + it('skips collections that already exist', async () => { + const connectionService = createConnectionService(); + const hasNext = jest.fn().mockResolvedValue(true); + const listCollections = jest.fn(() => ({ hasNext })); + const createCollection = jest.fn().mockResolvedValue(undefined); + const getModel = jest.fn().mockResolvedValue({ createCollection }); + + connectionService.getConnection = jest.fn().mockResolvedValue({ + db: { listCollections }, + }); + connectionService.getModel = getModel; + + await connectionService.ensureCollections(); + + expect(listCollections).toHaveBeenCalledTimes(modelDefinitions.length); + expect(getModel).not.toHaveBeenCalled(); + expect(createCollection).not.toHaveBeenCalled(); + }); +}); + describe('resolveMongoAppName', () => { it('identifies api environment and process for MongoDB connection tracking', () => { expect(resolveMongoAppName('staging', 1234)).toBe( diff --git a/apps/api/src/modules/global/database/connection.service.ts b/apps/api/src/modules/global/database/connection.service.ts index 9a27d46..c26e034 100644 --- a/apps/api/src/modules/global/database/connection.service.ts +++ b/apps/api/src/modules/global/database/connection.service.ts @@ -118,9 +118,32 @@ export class ConnectionService implements OnModuleInit { } } + public async ensureCollections(): Promise { + const connection = await this.getConnection(); + let createdCollectionCount = 0; + + for (const modelDefinition of modelDefinitions) { + const collectionExists = await this.collectionExists( + connection, + modelDefinition.collectionName, + ); + if (collectionExists) continue; + + const model = await this.getModel( + modelDefinition.name as keyof ModelTypes, + ); + await model.createCollection(); + createdCollectionCount += 1; + } + + this.logger.log( + `MongoDB collections ensured. registered=${modelDefinitions.length} created=${createdCollectionCount}`, + ); + } + public async onModuleInit() { - await this.getConnection().catch((error: unknown) => { - this.logError('Failed to initialize MongoDB connection', error); + await this.ensureCollections().catch((error: unknown) => { + this.logError('Failed to initialize MongoDB collections', error); }); } @@ -134,4 +157,18 @@ export class ConnectionService implements OnModuleInit { error instanceof Error ? error.stack : undefined, ); } + + private async collectionExists( + connection: mongoose.Connection, + collectionName: string, + ): Promise { + const database = connection.db; + if (!database) { + throw new Error('MongoDB database handle is unavailable.'); + } + + return database + .listCollections({ name: collectionName }, { nameOnly: true }) + .hasNext(); + } }