Created
January 14, 2022 07:08
-
-
Save GregOnNet/e7440c3203704dd220528b495f274d1c to your computer and use it in GitHub Desktop.
Starts and Stops mongo-memory-db
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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