This repository has been archived by the owner on Mar 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathindex.js
65 lines (57 loc) · 1.77 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
var AbstractClientStore = require('express-brute/lib/AbstractClientStore');
var xtend = require('xtend');
var moment = require('moment');
var MongoStore = module.exports = function (getCollection, options) {
AbstractClientStore.apply(this, arguments);
this.options = xtend({}, MongoStore.defaults, options);
var self = this;
getCollection(function (collection) {
self._collection = collection;
});
};
MongoStore.prototype = Object.create(AbstractClientStore.prototype);
MongoStore.prototype.set = function (key, value, lifetime, callback) {
var _id = this.options.prefix+key;
var expiration = lifetime ? moment().add(lifetime, 'seconds').toDate() : undefined;
this._collection.update({
_id: _id
}, {
_id: _id,
data: value,
expires: expiration
}, {
upsert: true
}, function () {
if (callback) callback.apply(this, arguments);
});
};
MongoStore.prototype.get = function (key, callback) {
var _id = this.options.prefix + key;
var collection = this._collection;
collection.findOne({ _id: _id }, function (err, doc) {
if (err) {
typeof callback == 'function' && callback(err, null);
} else {
var data;
if (doc && doc.expires < new Date()) {
collection.remove({ _id: _id }, {w: 0});
return callback();
}
if (doc) {
data = doc.data;
data.lastRequest = new Date(data.lastRequest);
data.firstRequest = new Date(data.firstRequest);
}
typeof callback == 'function' && callback(err, data);
}
});
};
MongoStore.prototype.reset = function (key, callback) {
var _id = this.options.prefix+key;
this._collection.remove({ _id: _id }, function () {
typeof callback == 'function' && callback.apply(this, arguments);
});
};
MongoStore.defaults = {
prefix: ''
};