-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (61 loc) · 1.82 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
/**
* @module cache-promise
*/
(function () {
"use strict";
var config = require('config'),
Q = require("q"),
utils = require("cacher-utils"),
cacheStorage = utils.getCacheStorage();
/**
* Cahe wrapper
*
* @param {(function)} myFunction
* @param {Array} args
* @param {number|object} options (if number options = expires)
* @return {*}
*
* @example
* var co = require('co'),
* wait = require('co-wait'),
* cacher = require('co-cacher');
*
* var testGenerator = function* testGenerator (a) {
* yield wait(1000);
* return a+1;
* };
*
* co(function *(){
* var result = yield cacher(testGenerator, [4], {expires: 30});
* console.log(result);
* }).catch(function(e) {throw e; });
*
*/
module.exports = function (myFunction, args, options) {
if (typeof options == 'object') {
} else {
var expires = options;
options = {};
options.expires = expires;
}
var time = options.expires || config.cache.expires;
var salt = options.salt || '';
var key = utils.keyMaker(myFunction.name, salt, args);
var deferred = Q.defer();
cacheStorage.get(key).then(function (value) {
if (typeof value != 'undefined' ) {
deferred.resolve(value);
} else {
myFunction.apply(myFunction,args).then(function (value) {
cacheStorage.set(key,value,time).then();
deferred.resolve(value);
},
deferred.reject
)
}
},
deferred.reject
);
return deferred.promise;
}
}());