-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.js
81 lines (65 loc) · 2.01 KB
/
db.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb:https://'+ process.env.MONGODB_USERNAME +':' + process.env.MONGODB_PASSWORD + '@' + process.env.MONGODB_URL;
const dbName = 'benchmark';
let db = null;
let dbClient = null;
const connectDb = async () => {
if (db) return db;
while (true) {
try {
const client = await MongoClient.connect(url, {
useNewUrlParser: true,
});
dbClient = client;
dbCon = client.db(dbName);
db = dbCon;
console.log('Connection to DB successful');
return dbCon;
}
catch (error) {
console.log('Could not connect to DB. Retry in 5s');
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
}
const findResults = async (query, projection) => {
const col = db.collection('results');
return col.find(query, projection).toArray();
}
const findOneResult = async (query, projection) => {
const col = db.collection('results');
return col.findOne(query, projection).toArray();
}
const insertResults = async (results) => {
const col = db.collection('results');
return col.insertMany(results);
}
const getAllConcurrencyIds = async () => {
const col = db.collection('results');
return col.distinct('concurrencyId');
}
const insertAggregations = async (aggregations) => {
const col = db.collection('aggregations');
return col.insertMany(aggregations);
}
function exitHandler() {
if (dbClient) dbClient.close();
process.exit()
}
//do something when app is closing
process.on('exit', exitHandler);
//catches ctrl+c event
process.on('SIGINT', exitHandler);
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', exitHandler);
process.on('SIGUSR2', exitHandler);
//catches uncaught exceptions
process.on('uncaughtException', exitHandler);
module.exports = {
insertResults,
findResults,
findOneResult,
connectDb,
insertAggregations,
getAllConcurrencyIds
}