1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | var assert = require('assert');
|
16 | var LRU = require('lru-cache');
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | function Cache(size, expiry, log, name) {
|
29 | assert.ok(size !== undefined);
|
30 | assert.ok(expiry !== undefined);
|
31 | this.size = size;
|
32 | this.expiry = expiry * 1000;
|
33 | this.log = log;
|
34 | this.name = (name ? name + ' ' : '');
|
35 | this.items = new LRU({ max: this.size });
|
36 | }
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | Cache.prototype.reset = function reset() {
|
44 | if (this.log) {
|
45 | this.log.trace('%scache reset', this.name);
|
46 | }
|
47 | this.items.reset();
|
48 | };
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | Cache.prototype.get = function get(key) {
|
57 | assert.ok(key !== undefined);
|
58 | var cached = this.items.get(key);
|
59 | if (cached) {
|
60 | if (((new Date()).getTime() - cached.ctime) <= this.expiry) {
|
61 | if (this.log) {
|
62 | this.log.trace('%scache hit: key="%s": %o', this.name, key, cached);
|
63 | }
|
64 | return cached.value;
|
65 | }
|
66 | }
|
67 | if (this.log) {
|
68 | this.log.trace('%scache miss: key="%s"', this.name, key);
|
69 | }
|
70 | return null;
|
71 | };
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 | Cache.prototype.set = function set(key, value) {
|
81 | assert.ok(key !== undefined);
|
82 | var item = {
|
83 | value: value,
|
84 | ctime: new Date().getTime()
|
85 | };
|
86 | if (this.log) {
|
87 | this.log.trace('%scache set: key="%s": %o', this.name, key, item);
|
88 | }
|
89 | this.items.set(key, item);
|
90 | return item;
|
91 | };
|
92 |
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 | Cache.prototype.del = function del(key) {
|
100 | if (this.log) {
|
101 | this.log.trace('%scache del: key="%s"', this.name, key);
|
102 | }
|
103 | this.items.del(key);
|
104 | };
|
105 |
|
106 |
|
107 | module.exports = Cache;
|