Skip to content

Instantly share code, notes, and snippets.

@GregOnNet
Created January 14, 2022 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GregOnNet/e7440c3203704dd220528b495f274d1c to your computer and use it in GitHub Desktop.
Save GregOnNet/e7440c3203704dd220528b495f274d1c to your computer and use it in GitHub Desktop.
Starts and Stops mongo-memory-db
import { ConfigService } from '@leocloud/shared';
import { DynamicModule, Inject, Module, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { connect, disconnect } from 'mongoose';
import { Subject } from 'rxjs';
const MONGO_DB_TESTING_COLLECTION_NAMES = 'MongoDbTestingCollectionNames';
const mongoDbIsBootstrapped = new Subject<void>();
@Module({})
export class MongoDbTestingModule implements OnApplicationBootstrap, OnApplicationShutdown {
private server: MongoMemoryServer;
private mongoose: typeof import('mongoose');
static bootstrap(collectionNames: string[]): DynamicModule {
return {
module: MongoDbTestingModule,
providers: [
{
provide: MONGO_DB_TESTING_COLLECTION_NAMES,
useValue: collectionNames,
},
],
};
}
constructor(@Inject(MONGO_DB_TESTING_COLLECTION_NAMES) private collectionNames: string[], private configService: ConfigService) {}
async onApplicationBootstrap() {
await this.createServer();
await this.createCollections();
mongoDbIsBootstrapped.next();
}
async onApplicationShutdown(signal?: string) {
await disconnect();
await this.server.stop();
}
private async createServer() {
this.server = await MongoMemoryServer.create();
const uri = this.server.getUri();
// Make uri available so that DatabaseModule can connect to MongoDB
process.env.MONGODB_URI = uri;
this.mongoose = await connect(uri, { dbName: this.configService.get('MONGODB_DBNAME') });
}
private async createCollections() {
this.collectionNames.forEach(async collectionName => await this.mongoose.connection.createCollection(collectionName));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment