Ensure Mongo collections on startup
This commit is contained in:
1 parent
fafacec781
commit
1df1cd54f8
2 files changed
+92
-2
No files matched your search
@@ -1,8 +1,10 @@
|
|||||||
import {
|
import {
|
||||||
|
ConnectionService,
|
||||||
resolveMongoAppName,
|
resolveMongoAppName,
|
||||||
resolveMongoConnectionOptions,
|
resolveMongoConnectionOptions,
|
||||||
resolveMongoDbName,
|
resolveMongoDbName,
|
||||||
} from './connection.service';
|
} from './connection.service';
|
||||||
|
import { modelDefinitions } from './schemas';
|
||||||
|
|
||||||
describe('resolveMongoDbName', () => {
|
describe('resolveMongoDbName', () => {
|
||||||
it('uses production database only for prod', () => {
|
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', () => {
|
describe('resolveMongoAppName', () => {
|
||||||
it('identifies api environment and process for MongoDB connection tracking', () => {
|
it('identifies api environment and process for MongoDB connection tracking', () => {
|
||||||
expect(resolveMongoAppName('staging', 1234)).toBe(
|
expect(resolveMongoAppName('staging', 1234)).toBe(
|
||||||
|
|||||||
@@ -118,9 +118,32 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async ensureCollections(): Promise<void> {
|
||||||
|
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() {
|
public async onModuleInit() {
|
||||||
await this.getConnection().catch((error: unknown) => {
|
await this.ensureCollections().catch((error: unknown) => {
|
||||||
this.logError('Failed to initialize MongoDB connection', error);
|
this.logError('Failed to initialize MongoDB collections', error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,4 +157,18 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
error instanceof Error ? error.stack : undefined,
|
error instanceof Error ? error.stack : undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async collectionExists(
|
||||||
|
connection: mongoose.Connection,
|
||||||
|
collectionName: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const database = connection.db;
|
||||||
|
if (!database) {
|
||||||
|
throw new Error('MongoDB database handle is unavailable.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return database
|
||||||
|
.listCollections({ name: collectionName }, { nameOnly: true })
|
||||||
|
.hasNext();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user