forked from andrewjstone/cacheit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
85 lines (77 loc) · 1.86 KB
/
cache.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
var redis = require('redis');
var Cache = module.exports = function() {
var self = this;
this.client = redis.createClient();
this.client.on('error', function(err) {
console.error('redis client error'+err);
throw(err);
});
this.client.on('end', function() {
self.disconnects++;
self.connected = false;
});
this.client.on('connect', function() {
self.connects++;
self.connected = true;
});
this.hits = 0;
this.misses = 0;
this.errors = 0;
this.default_ttl = 300; // 5 minutes
this.disconnects = 0;
this.connects = 0;
this.connected = false;
};
Cache.prototype.setHash =
Cache.prototype.set = function(key, value, ttl, callback) {
if (typeof ttl === 'function') {
callback = ttl;
ttl = this.default_ttl;
}
ttl = ttl || this.default_ttl;
var self = this;
var op = typeof value === 'string' ? 'set' : 'hmset';
this.client[op](key, value, function(err) {
if (err) {
self.errors++;
return callback(err);
}
self.client.expire(key, ttl, function(err) {
if (err) self.errors++;
if (callback) callback(err);
});
});
};
Cache.prototype.delete = function(key, callback) {
this.client.del(key, function(err) {
if (err) {
self.errors++;
return callback(err);
}
callback(null);
});
};
Cache.prototype.getHash = function(key, callback) {
this._get(key, 'hgetall', callback);
};
Cache.prototype.get = function(key, callback) {
this._get(key, 'get', callback);
};
Cache.prototype._get = function(key, op, callback) {
var self = this;
this.client[op](key, function(err, value) {
if (err) {
self.errors++;
return callback(err);
}
if (!value) {
self.misses++;
return callback();
}
self.hits++;
return callback(err, value);
});
};
Cache.prototype.total_keys = function(callback) {
this.client.dbsize(callback);
};