forked from v4l3r10/node-cache-manager-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
351 lines (311 loc) · 8.34 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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
'use strict';
/**
* Module dependencies.
*/
const Client = require('mongodb').MongoClient;
const zlib = require('zlib');
const _ = require('lodash');
const validOptionNames = ['poolSize', 'ssl', 'sslValidate', 'sslCA', 'sslCert',
'sslKey', 'sslPass', 'sslCRL', 'autoReconnect', 'noDelay', 'keepAlive', 'connectTimeoutMS', 'family',
'socketTimeoutMS', 'reconnectTries', 'reconnectInterval', 'ha', 'haInterval',
'replicaSet', 'secondaryAcceptableLatencyMS', 'acceptableLatencyMS',
'connectWithNoPrimary', 'authSource', 'w', 'wtimeout', 'j', 'forceServerObjectId',
'serializeFunctions', 'ignoreUndefined', 'raw', 'bufferMaxEntries',
'readPreference', 'pkFactory', 'promiseLibrary', 'readConcern', 'maxStalenessSeconds',
'loggerLevel', 'logger', 'promoteValues', 'promoteBuffers', 'promoteLongs',
'domainsEnabled', 'keepAliveInitialDelay', 'checkServerIdentity', 'validateOptions', 'appname', 'auth', 'useNewUrlParser',
'useUnifiedTopology'
];
/**
* MongoStore constructor.
*
* @param {Object} options
* @api public
*/
class MongoStore {
constructor(args) {
var store = this;
store.uri = (args.uri) ? args.uri : 'mongodb://localhost:27017/cache';
store.options = (args.options) ? args.options : {};
store.MongoOptions = store.options;
store.MongoOptions.ttl = (store.MongoOptions.ttl) ? store.MongoOptions.ttl : 60 * 1000;
store.MongoOptions.promiseLibrary = Promise;
store.MongoOptions.useNewUrlParser = true;
store.MongoOptions.useUnifiedTopology = true;
store.name = 'mongodb';
store.expireKey = 'expire';
store.db = store.MongoOptions.db;
store.coll = store.MongoOptions.collection || 'cacheman';
store.compression = store.MongoOptions.compression || false;
return this;
}
getCollection() {
var store = this;
return new Promise((resolve, reject) => {
try {
if (store.client && store.collection)
return resolve(store.collection);
return resolve(store.initClient());
} catch(error) {
reject(error);
}
});
}
initClient() {
var store = this;
let uri = store.uri;
return Client.connect(uri, _.pick(store.MongoOptions, validOptionNames)
).then((client) => {
return client.db(store.db);
}).then((db) => {
store.client = db;
return store.initColl();
}).then(() => {
return store.collection;
}).catch((err) => {
console.log(err);
throw err;
});
}
/**
* Init Collection on db
*/
initColl() {
var self = this;
return self.checkColl()
.then((collection) => {
if (collection) {
self.collection = collection;
return collection;
}
//if not exist create it with index
return self.client.createCollection(self.coll).then((coll) => {
self.collection = coll;
//create Expire index that hook TTL when date in expire is lower than expire field
return self.collection.createIndex('expire', {
expireAfterSeconds: 0
});
}).then(() => {
return self.collection.createIndex('key', {
unique: true
});
})
})
}
/**
* Promisify collection check method
*/
checkColl() {
var self = this;
return new Promise((resolve, reject) => {
self.client.collection(self.coll, { strict: true }, (err, coll) => {
//if err is collectio not exist resolve with null value
if (err && err.message.indexOf('not exist') > -1)
return resolve();
else if (err)
return reject(err);
return resolve(coll);
});
});
}
/**
* Compress data value.
*
* @param {Object} data
* @api public
*/
compress(data) {
return new Promise((resolve, reject) => {
// Data is not of a "compressable" type (currently only Buffer)
if (!Buffer.isBuffer(data)) {
return reject(new Error('Data is not of a "compressable" type (currently only Buffer)'));
}
zlib.gzip(data, (err, val) => {
if (err)
return reject(err);
return resolve(val);
});
});
}
/**
* Decompress data value.
*
* @param {Object} value
* @api public
*/
decompress(value) {
return new Promise((resolve, reject) => {
value = (value.buffer && Buffer.isBuffer(value.buffer)) ? value.buffer : value;
zlib.gunzip(value, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
/**
* Get an entry.
*
* @param {String} key
* @param {} options
* @param {fn} cb
* @api public
*/
get(key, options, cb) {
var store = this;
if (typeof options === 'function') {
cb = options;
options = {};
}
if (cb === undefined) {
return new Promise(function (resolve, reject) {
store.get(key, options, function (err, result) {
err ? reject(err) : resolve(result)
})
})
}
store.getCollection()
.then((collection) => {
return collection.findOne({
key: key
});
}).then((data) => {
if (!data)
return cb();
if (data.expire < (new Date())) return cb();
if (data.compressed)
return cb(null, store.decompress(data.value));
return cb(null, data.value);
}).catch(err => cb(err));
}
/**
* Set an entry.
*
* @param {String} key
* @param {Mixed} val
* @param {Object} options
* @param {fn} cb
* @api public
*/
set(key, val, options, cb) {
const store = this;
if (typeof options === 'function') {
cb = options;
options = {};
}
if (cb === undefined) {
return new Promise(function (resolve, reject) {
store.set(key, val, options, function (err, result) {
err ? reject(err) : resolve(result)
})
})
}
var data = {
key: key,
value: val
};
data.expire = new Date();
//if new ttl generate expire Date else use standard TTL
if (options && options.ttl)
data.expire.setTime(data.expire.getTime() + (options.ttl * 1000));
else
data.expire.setTime(data.expire.getTime() + (store.MongoOptions.ttl * 1000));
const query = {
key: key
};
const opt = {
upsert: true,
w: 1
};
store.getCollection()
.then((collection) => {
if (store.compression) {
return store.compress(data.value)
.then((value) => {
data.value = value;
return collection.findOneAndUpdate(query, {
'$set': data
}, opt);
});
}
return collection.findOneAndUpdate(query, {
'$set': data
}, opt);
}).then((data) => {
return cb(null, data);
}).catch(err => cb(err));
}
/**
* Delete an entry.
*
* @param {String} key
* @param {Object} options
* @param {fn} cb
* @api public
*/
del(key, options, cb) {
var store = this;
if (typeof options === 'function') {
cb = options;
options = {};
}
if (cb === undefined) {
return new Promise(function (resolve, reject) {
store.del(key, options, function (err, result) {
err ? reject(err) : resolve(result)
})
})
}
store.getCollection()
.then((collection) => {
return collection.deleteOne({
key: key
});
}).then((r) => {
if (r.deleteCount)
return cb(null, true);
return cb(null, false);
}).catch(err => cb(err));
}
/**
* Clear all entries for this bucket.
*
* @param {String} key
* @param {fn} cb
* @api public
*/
reset(key, cb) {
var store = this;
if (typeof key === 'function') {
cb = key;
key = {};
}
if (cb === undefined) {
return new Promise(function (resolve, reject) {
store.reset(key, function (err, result) {
err ? reject(err) : resolve(result)
})
})
}
store.getCollection()
.then((collection) => {
return collection.deleteMany({}, {
w: 1
});
}).then(() => {
return cb(null, true);
})
.catch(err => cb(err));
}
isCacheableValue(value) {
return value !== null && value !== undefined;
}
}
/**
* Export `MongoStore`.
*/
exports = module.exports = {
create: (args) => {
return new MongoStore(args);
}
};