-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpeditious-memory-engine.js
More file actions
122 lines (102 loc) · 2.44 KB
/
expeditious-memory-engine.js
File metadata and controls
122 lines (102 loc) · 2.44 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
'use strict';
var ExpeditiousEngine = require('expeditious').ExpeditiousEngine;
module.exports = function () {
// This is our cache storage object
var data = {};
// Create an engine that inherts from ExpeditiousEngine
var engine = Object.create(ExpeditiousEngine.prototype);
/**
* Set the given key-value pair with the given expire time
* @param {String} key
* @param {String} val
* @param {Number} expire
* @param {Function} callback
*/
engine.set = function (key, val, expire, callback) {
// We need to store entries as Objects to track expiry etc.
data[key] = {
val: val,
expire: Date.now() + expire,
timer: setTimeout(
engine.del.bind(
engine,
key,
function noop (/* err */) {}
),
expire
)
};
setImmediate(function () {
callback(null, null);
});
};
/**
* Get the value for a specific key from the cache
* @param {String} key
* @param {Function} callback
*/
engine.get = function (key, callback) {
setImmediate(function () {
if (data[key]) {
callback(null, data[key].val);
} else {
callback(null, null);
}
});
};
/**
* Delete the given key-value pair from the cache
* @param {String} key
* @param {Function} callback
*/
engine.del = function (key, callback) {
var entry = data[key];
/* istanbul ignore else */
if (entry) {
delete data[key];
clearTimeout(entry.timer);
}
setImmediate(function () {
callback(null, null);
});
};
/**
* Return keys matching the provided pattern
* @param {Function} callback
*/
engine.keys = function (callback) {
setImmediate(function () {
callback(null, Object.keys(data));
});
};
/**
* Returns the milliseconds left before the given key expires
* @param {String} key
* @param {Function} callback
*/
engine.ttl = function (key, callback) {
var entry = data[key]
, ret = null;
if (entry) {
ret = entry.expire - Date.now();
}
setImmediate(function () {
callback(null, ret);
});
};
/**
* Delete all cache entries
* @param {Function} callback
*/
engine.flush = function (ns, callback) {
data = {};
if (typeof ns === 'function') {
callback = ns;
ns = null;
}
setImmediate(function () {
callback(null, null);
});
};
return engine;
};