-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathindex.js
436 lines (351 loc) · 9.06 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
'use strict';
/**
* Module dependencies.
*/
import ms from 'ms';
/**
* Module constants.
*/
const engines = ['memory', 'redis', 'mongo', 'file'];
/**
* Cacheman base error class.
*
* @constructor
* @param {String} message
* @api private
*/
class CachemanError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
this.message = message;
Error.captureStackTrace(this, this.constructor);
}
}
/**
* Helper to allow all async methods to support both callbacks and promises
*/
function maybePromised(_this, callback, wrapped) {
if ('function' === typeof callback) {
// Call wrapped with unmodified callback
wrapped(callback);
// Return `this` to keep the same behaviour Cacheman had before promises were added
return _this;
} else {
let _Promise = _this.options.Promise;
if ('function' !== typeof _Promise) {
throw new CachemanError('Promises not available: Please polyfill native Promise before creating a Cacheman object, pass a Promise library as a Cacheman option, or use the callback interface')
}
if (_Promise.fromCallback) {
// Bluebird's fromCallback, this is faster than new Promise
return _Promise.fromCallback(wrapped)
}
// Standard new Promise based wrapper for native Promises
return new _Promise(function(resolve, reject) {
wrapped(function(err, value) {
if (err) {
reject(err);
} else {
resolve(value);
}
});
});
}
}
/**
* Cacheman constructor.
*
* @param {String} name
* @param {Object} options
* @api public
*/
export default class Cacheman {
/**
* Class constructor method.
*
* @param {String} name
* @param {Object} [options]
* @return {Cacheman} this
* @api public
*/
constructor(name, options = {}) {
if (name && 'object' === typeof name) {
options = name;
name = null;
}
const _Promise = options.Promise || (function() {
try {
return Promise;
} catch (e) {}
})();
let {
prefix = 'cacheman',
engine = 'memory',
delimiter = ':',
ttl = 60
} = options;
if ('string' === typeof ttl) {
ttl = Math.round(ms(ttl)/1000);
}
prefix = [prefix, name || 'cache', ''].join(delimiter);
this.options = { ...options, Promise: _Promise, delimiter, prefix, ttl, count: 1000 };
this._prefix = prefix;
this._ttl = ttl;
this._fns = [];
this.engine(engine);
}
/**
* Set get engine.
*
* @param {String} engine
* @param {Object} options
* @return {Cacheman} this
* @api public
*/
engine(engine, options) {
if (!arguments.length) return this._engine;
const type = typeof engine;
if (! /string|function|object/.test(type)) {
throw new CachemanError('Invalid engine format, engine must be a String, Function or a valid engine instance');
}
if ('string' === type) {
let Engine;
if (~Cacheman.engines.indexOf(engine)) {
engine = `cacheman-${engine}`;
}
try {
Engine = require(engine);
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND') {
throw new CachemanError(`Missing required npm module ${engine}`);
} else {
throw e;
}
}
this._engine = new Engine(options || this.options, this);
} else if ('object' === type) {
['get', 'set', 'del', 'clear'].forEach(key => {
if ('function' !== typeof engine[key]) {
throw new CachemanError('Invalid engine format, must be a valid engine instance');
}
})
this._engine = engine;
} else {
this._engine = engine(options || this.options, this);
}
return this;
}
/**
* Wrap key with prefix.
*
* @param {String} key
* @return {String}
* @api private
*/
key(key) {
if ( Array.isArray(key) ) {
key = key.join(this.options.delimiter);
}
return (this.options.engine === 'redis') ? key : this._prefix + key;
}
/**
* Sets up namespace middleware.
*
* @return {Cacheman} this
* @api public
*/
use(fn) {
this._fns.push(fn);
return this;
}
/**
* Executes the cache middleware.
*
* @param {String} key
* @param {Mixed} data
* @param {Number} ttl
* @param {Function} fn
* @api private
*/
run(key, data, ttl, fn) {
const fns = this._fns.slice(0);
if (!fns.length) return fn(null);
const go = i => {
fns[i](key, data, ttl, (err, _data, _ttl, _force) => {
// upon error, short-circuit
if (err) return fn(err);
// if no middleware left, summon callback
if (!fns[i + 1]) return fn(null, _data, _ttl, _force);
// go on to next
go(i + 1);
});
}
go(0);
}
/**
* Set an entry.
*
* @param {String} key
* @param {Mixed} data
* @param {Number} ttl
* @param {Function} [fn]
* @return {Cacheman} this
* @api public
*/
cache(key, data, ttl, fn) {
if ('function' === typeof ttl) {
fn = ttl;
ttl = null;
}
return maybePromised(this, fn, (fn) => {
this.get(key, (err, res) => {
this.run(key, res, ttl, (_err, _data, _ttl, _force) => {
if (err || _err) return fn(err || _err);
let force = false;
if ('undefined' !== typeof _data) {
force = true;
data = _data;
}
if ('undefined' !== typeof _ttl) {
force = true;
ttl = _ttl;
}
if ('undefined' === typeof res || force) {
return this.set(key, data, ttl, fn);
}
fn(null, res);
});
});
});
}
/**
* Get an entry.
*
* @param {String} key
* @param {Function} [fn]
* @return {Cacheman} this
* @api public
*/
get(key, fn) {
return maybePromised(this, fn, (fn) =>
this._engine.get(this.key(key), fn));
}
/**
* Set an entry.
*
* @param {String} key
* @param {Mixed} data
* @param {Number} ttl
* @param {Function} [fn]
* @return {Cacheman} this
* @api public
*/
set(key, data, ttl, fn) {
if ('function' === typeof ttl) {
fn = ttl;
ttl = null;
}
if ('string' === typeof ttl) {
ttl = Math.round(ms(ttl)/1000);
}
return maybePromised(this, fn, (fn) => {
if ('string' !== typeof key && !Array.isArray(key)) {
return process.nextTick(() => {
fn(new CachemanError('Invalid key, key must be a string or array.'));
});
}
if ('undefined' === typeof data) {
return process.nextTick(fn);
}
return this._engine.set(this.key(key), data, ttl || this._ttl, fn);
});
}
/**
* Delete an entry.
*
* @param {String} key
* @param {Function} [fn]
* @return {Cacheman} this
* @api public
*/
del(key, fn) {
if ('function' === typeof key) {
fn = key;
key = '';
}
return maybePromised(this, fn, (fn) =>
this._engine.del(this.key(key), fn));
}
/**
* Clear all entries.
*
* @param {String} key
* @param {Function} [fn]
* @return {Cacheman} this
* @api public
*/
clear(fn) {
return maybePromised(this, fn, (fn) =>
this._engine.clear(fn));
}
/**
* Wraps a function in cache. I.e., the first time the function is run,
* its results are stored in cache so subsequent calls retrieve from cache
* instead of calling the function.
*
* @param {String} key
* @param {Function} work
* @param {Number} ttl
* @param {Function} [fn]
* @api public
*/
wrap(key, work, ttl, fn) {
// Allow work and ttl to be passed in the oposite order to make promises nicer
if ('function' !== typeof work && 'function' === typeof ttl) {
[ttl, work] = [work, ttl];
}
if ('function' === typeof ttl) {
fn = ttl;
ttl = null;
}
return maybePromised(this, fn, (fn) => {
this.get(key, (err, res) => {
if (err || res) return fn(err, res);
let next = (err, data) => {
if (err) return fn(err);
this.set(key, data, ttl, err => {
fn(err, data);
});
// Don't allow callbacks to be called twice
next = () => {
process.nextTick(() => {
throw new CachemanError('callback called twice');
});
};
}
if ( work.length >= 1 ) {
const result = work((err, data) => next(err, data));
if ('undefined' !== typeof result) {
process.nextTick(() => {
throw new CachemanError('return value cannot be used when callback argument is used');
});
}
} else {
try {
const result = work();
if ('object' === typeof result && 'function' === typeof result.then) {
result
.then((value) => next(null, value))
.then(null, (err) => next(err));
} else {
next(null, result);
}
} catch (err) {
next(err);
}
}
});
});
}
}
Cacheman.engines = engines;