-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongo-state-storage.js
66 lines (61 loc) · 1.66 KB
/
mongo-state-storage.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
/* eslint-disable no-useless-catch */
/* eslint-disable no-console */
/* eslint-disable class-methods-use-this */
const config = require('config');
const { MongoClient } = require('mongodb');
const clusterUrl = `${config.get('mongo.host')}:${config.get('mongo.port')}`;
const url = `mongodb://${clusterUrl}/`;
class MongoDbStore {
async load(fn) {
let client = null;
let data = null;
try {
client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = client.db(config.get('mongo.database'));
data = await db.collection('trailing-trade-migrations').find().toArray();
if (data.length !== 1) {
console.log(
'Cannot read migrations from database. If this is the first time you run migrations, then this is normal.'
);
return fn(null, {});
}
} catch (err) {
throw err;
} finally {
client.close();
}
return fn(null, data[0]);
}
async save(set, fn) {
let client = null;
let result = null;
try {
client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = client.db(config.get('mongo.database'));
result = await db.collection('trailing-trade-migrations').updateMany(
{},
{
$set: {
lastRun: set.lastRun
},
$push: {
migrations: { $each: set.migrations }
}
},
{ upsert: true }
);
} catch (err) {
throw err;
} finally {
client.close();
}
return fn(null, result);
}
}
module.exports = MongoDbStore;