-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (39 loc) · 1.16 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
var hash = require('object-hash'),
Redis = require('redis'),
_ = require('lodash');
var defaultConfig = {
redisPort: 6379,
redisHost: '127.0.0.1',
redisDatabase: 0,
cacheTime: 5 //seconds
}
function Mutate (client, options) {
var config = _.extend(defaultConfig, options || {}),
redis = Redis.createClient(config.redisPort, config.redisHost);
redis.select(config.redisDatabase);
client._search = client.search;
client.search = function (params, cb) {
if (params.noCache) {
var noCache = true;
delete params.noCache;
}
var hid = hash(params);
if (noCache) {
searchAndPersist(params, hid, cb);
} else {
redis.get(hid, function (err, data) {
if (err) return cb(err);
if (data) return cb(null, JSON.parse(data));
searchAndPersist(params, hid, cb);
});
}
};
function searchAndPersist (params, hid, callback) {
client._search(params, function (err, data) {
if (err) return callback(err);
setImmediate(function (){ return callback(err, data); });
redis.set(hid, JSON.stringify(data), 'EX', config.cacheTime);
});
}
}
module.exports = Mutate