-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (52 loc) · 1.44 KB
/
index.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
const MongoClient = require('mongodb').MongoClient
const MongoDBConnector = function ({connectionString, database}) {
this.connectionString = connectionString
this.database = database
}
MongoDBConnector.prototype.connect = function () {
return new Promise((resolve, reject) => {
MongoClient.connect(this.connectionString, (err, client) => {
if (err) return reject(err)
this.client = client
this.db = client.db(this.database)
resolve(this.db)
})
})
}
MongoDBConnector.prototype.disconnect = function () {
this.client.close()
}
MongoDBConnector.prototype.get = function ({
collection,
timestampFrom,
timestampTo
}) {
let options = {}
if (typeof timestampFrom === 'number') {
options.timestamp = {
$gte: timestampFrom
}
}
if (typeof timestampTo === 'number') {
options.timestamp = options.timestamp || {}
options.timestamp.$lte = timestampTo
}
return new Promise((resolve, reject) => {
this.db.collection(collection)
.find(options)
.sort({timestamp: 1})
.toArray((err, results) => {
if (err) return reject(err)
resolve(results)
})
})
}
MongoDBConnector.prototype.insert = function ({collection, results}) {
return new Promise((resolve, reject) => {
this.db.collection(collection).insertMany(results, (err, response) => {
if (err) return reject(err)
resolve(response)
})
})
}
module.exports = MongoDBConnector