-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-mongodb.ts
36 lines (30 loc) · 901 Bytes
/
test-mongodb.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import logger from '../utils/logger';
let mongodbServer: MongoMemoryServer;
const connect = async () => {
mongodbServer = await MongoMemoryServer.create();
const testMongoDBURI = mongodbServer.getUri();
try {
if (mongoose.connection.readyState === 0) {
await mongoose.connect(testMongoDBURI);
logger.info('Connected to TEST MongoDB');
}
} catch (error) {
const message = logger.getErrorMessage(error);
logger.error('Error connecting to test MongoDB: ', message);
}
};
const close = async () => {
await mongoose.disconnect();
await mongodbServer.stop();
};
const clear = async () => {
const { collections } = mongoose.connection;
Object.keys(collections).forEach((key) => collections[key].deleteMany({}));
};
export default {
connect,
close,
clear,
};