-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
107 lines (95 loc) · 2.77 KB
/
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"use strict";
const Promise = require('bluebird');
const mongoClient = require('mongodb').MongoClient;
const _ = require('lodash');
let debug = require('debug')('storage');
let connection;
/**
* @returns {Promise}
*/
const connect = function() {
// If connection already exists, use existing connection.
// It is recommended to only connect once and reuse that one connection: http://stackoverflow.com/questions/10656574
let promise;
if (connection) {
promise = Promise.resolve(connection);
// If connection is not yet created, connect and store resulting connection.
} else {
promise = mongoClient.connect(process.env.MONGODB_URI).then(function(db) {
// Store connection
connection = db;
return db;
});
}
return promise;
};
const insert = function(collectionName, items) {
return connect().then(function(db) {
return db.collection(collectionName).insert(items);
});
};
const update = function(collectionName, query, changes) {
return connect().then(function(db) {
return db.collection(collectionName).updateMany(query, changes);
});
};
/**
*
* @param {String} collectionName
* @param {Object} query
* @param {String|Array|Object} [sorter]
* @param {Number} [limit]
* @param {Number} [skip]
* @returns {*}
*/
const find = function(collectionName, query, sorter, limit, skip) {
return connect().then(function(db) {
let cursor = db.collection(collectionName).find(query);
if (sorter) {
sorter = _.isString(sorter) ? {[sorter]: 1} : sorter;
cursor.sort(sorter);
}
if (skip) {
cursor.skip(skip);
}
if (limit) {
cursor.limit(limit);
}
return cursor.toArray();
});
};
const remove = function(collectionName, query) {
return connect().then(function(db) {
return db.collection(collectionName).remove(query);
});
};
const count = function(collectionName, query) {
return connect().then(function(db) {
return db.collection(collectionName).count(query);
});
};
const distinct = function(collectionName, field) {
return connect().then(function(db) {
return db.collection(collectionName).distinct(field)
});
};
const drop = function(collectionName) {
return connect()
.then(function(db) {
return db.collection(collectionName).drop();
})
// Collection.drop will throw exception if collection does not exist. Catch the exception and resolve promise anyway.
.catch(function() {
return true;
});
};
module.exports = {
connect: connect,
insert: insert,
update: update,
find: find,
remove: remove,
count: count,
distinct: distinct,
drop: drop
};