This repository has been archived by the owner on Dec 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (88 loc) · 3.31 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
'use strict';
var cache = require("memory-cache");
var objectAssign = require('object-assign');
module.exports = function(options){
var globalOptions = objectAssign({
time : 1000*60*5,// default time of 5 minutes
autoUpdate : false, // should update automaticaly after expire
debug : false // enable debug
}, options);
return {
get : function(key, generator, callback, options){
if(typeof key !== 'string' && !(key instanceof String)){
throw new Error('Cache key must be a string');
}
if(typeof generator !== 'function'){
throw new Error('Cache generator must be a function');
}
if(typeof callback !== 'undefined' && typeof callback !== 'function'){
if(typeof options !== 'undefined'){
throw new Error('Cache callback must be a function');
}else{
options = callback;
callback = undefined;
}
}
if(!isNaN(parseFloat(options))){
options = {
time : options
}
}
options = objectAssign(globalOptions, options);
var args = cache.get(key);
if(args === null){
if(options.debug){
console.log("Cache: "+key+" - Getting data, next time in "+options.time);
}
if(generator){
var cacher = function(){
cache.put(key, arguments, options.time);
if(callback){
callback.apply(null, arguments);
}
};
if(generator.length > 0){
return new Promise(function(res, rej){
var resolver = function(){
cacher.apply(null, arguments);
res(arguments[0]);
};
generator(resolver);
});
}else{
try{
var prom = Promise.resolve(generator());
prom.then(function(args){
cacher(args);
}).catch(function(e){
if(callback){
callback(e);
}
});
return prom;
}catch(e){
if(callback){
callback(e);
}
return Promise.reject(e);
}
}
}
}else{
if(options.debug){
console.log("Cache: "+key+" - Using cached data");
}
if(callback){
callback.apply(null, args);
}
return Promise.resolve(args[0]);
}
},
del : function(key){
return cache.del(key);
},
clear : function(){
return cache.clear();
}
}
}