-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathttl.js
252 lines (215 loc) · 5.23 KB
/
ttl.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
/**
* Module dependencies.
*/
var Model = require('mongoose').Model
, ms = require('ms')
/**
* Exports.
*/
module.exports = exports = ttl;
/**
* Mongoose-TTL Plugin
*
* Provides timespan support for documents.
*
* Options:
* ttl: the time each doc should live in the db (default 60 seconds)
* interval: how often the expired doc reaper runs (default 5 mins)
* reap: enable the expired doc reaper (default true)
* onReap: callback passed to reaper execution
*
* Example:
*
* var schema = new Schema({..});
* schema.plugin(ttl, { ttl: 5000 });
*
* The ttl option supports the ms module by @guille meaning
* we can specify ttls with friendlier syntax. Example:
*
* value milliseconds
* ========================
* '2d' 172800000
* '1.5h' 5400000
* '1h' 3600000
* '1m' 60000
* '5s' 5000
* '500ms' 500
* 100 100
*
* The expired document reaper can be disabled by passing `reap: false`.
* Useful when working in multi-core environments when we only want one
* process executing it.
*
* var schema = new Schema({..});
* schema.plugin(ttl, { ttl: 5000, reap: false });
* var Cache = db.model('Cache', schema);
* if (isMyWorker) Cache.startTTLReaper();
*
* The reaper can also be stopped.
*
* Cache.stopTTLReaper();
*
* Time-to-live is specified at the collection level, however
* it can also be overridden for a given document.
*
* var cache = new Cache;
* cache.ttl = '2m' // lives for two minutes
* cache.save();
*
* We can also reset the ttl for a given document to its
* default plugin state.
*
* cache.resetTTL();
*
* @param {Schema} schema
* @param {Object} options
*/
function ttl (schema, options) {
options || (options = {});
var key = '__ttl'
, overridden = '__ttlOverride'
, ttl = options.ttl || 60000
, interval = options.interval || 60000*5
, reap = false !== options.reap
, onReap = 'function' == typeof options.onReap
? options.onReap
: undefined
var o = {};
o[key] = Date;
schema.add(o);
schema.index(key, { background: true });
schema.pre('save', function (next) {
if (overridden in this) {
// nothing to do
} else {
this[key] = fromNow();
}
next();
});
/**
* startTTLReaper
*
* Starts reaping expired docs from the db.
*/
schema.statics.startTTLReaper = function startTTLReaper () {
if (key in this) return;
var self = this;
self[key] = setInterval((function remove () {
self
.remove()
.where(key).lte(new Date)
.exec(onReap);
return remove;
})(), interval);
}
/**
* stopTTLReaper
*
* Stops removing expired docs from the db.
*/
schema.statics.stopTTLReaper = function stopTTLReapter () {
clearInterval(this[key]);
delete this[key];
};
/**
* Listen to Model.init.
*/
schema.on('init', init);
/**
* init
*
* Hook into all model queries to include the TTL
* filter and kick off the expired doc reaper if
* enabled.
* @private
*/
function init (model) {
if (model.__ttl) return;
var distinct_ = model.distinct;
model.distinct = function distinct (field, cond, cb) {
applyTTL(cond);
return distinct_.call(model, field, cond, cb);
}
'findOne find count'.split(' ').forEach(function (method) {
var fn = model[method];
model[method] = function (cond, fields, opts, cb) {
if (!cond) {
cond = {};
} else if ('function' == typeof cond) {
cb = cond;
cond = {};
}
applyTTL(cond);
return fn.call(model, cond, fields, opts, cb);
}
});
'where $where'.split(' ').forEach(function (method) {
var fn = model[method];
model[method] = function () {
var query = fn.apply(this, arguments)
, cond = {};
applyTTL(cond);
return query.find(cond);
}
});
if (reap) {
model.startTTLReaper();
}
}
/**
* Getters/setters
*/
var virt = schema.virtual('ttl');
virt.get(function () {
if (this[key]) return this[key];
this.ttl = ttl;
return this.ttl;
});
virt.set(function (val) {
if ('reset' == val) return this.resetTTL();
this[overridden] = arguments.length ? val : ttl;
return this[key] = fromNow(this[overridden]);
});
/**
* resetTTL
*
* Resets this documents ttl to the default specified
* in the plugin options or plugin default.
*/
schema.methods.resetTTL = function resetTTL () {
delete this._doc[key];
delete this[overridden];
}
/**
* fromNow
* @private
*/
function fromNow (val) {
var v = arguments.length ? val : ttl;
return new Date(Date.now() + ms(v));
}
/**
* Applies ttl to query conditions.
* @private
*/
function applyTTL (cond) {
if (cond[key]) {
cond.$and || (cond.$and = []);
var a = {};
a[key] = cond[key];
cond.$and.push(a);
var b = {};
b[key] = { $gt: new Date };
cond.$and.push(b);
delete cond[key];
} else {
cond[key] = { $gt: new Date };
}
}
}
/**
* Expose version.
*/
exports.version = JSON.parse(
require('fs').readFileSync(__dirname + '/../package.json')
).version;