-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (47 loc) · 1.33 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
'use strict';
const cache = require('memory-cache');
class Cacherole {
constructor() {
this.Cacherole = Cacherole;
Object.defineProperty(this, 'cache', {
value: new cache.Cache(),
configurable: false,
writable: false
});
}
put(options) {
// Extract parameters from options object
let action, time, binding;
if (typeof options === 'function') {
action = options;
} else if (typeof options === 'object' && options !== null) {
({ action, time, binding } = options);
if (typeof action !== 'function') {
throw new TypeError('No valid function argument provided for cacherole put method call');
}
if (binding !== undefined) {
action = action.bind(binding);
}
} else {
throw new TypeError('Invalid options argument in cacherole put method call');
}
// Set up the cache wrapper for the action
const wrapper = (key, timeoutCallback) => {
if (typeof key !== 'string') {
throw TypeError('Key value must be a string');
}
const value = this.cache.get(key);
if (value !== null) {
return () => value;
} else {
return (...params) => this.cache.put(key, action(...params), time, timeoutCallback);
}
};
wrapper.update = (key, timeoutCallback) => {
this.cache.del(key);
return wrapper(key, timeoutCallback);
};
return wrapper;
}
}
module.exports = new Cacherole();