UNPKG

2.55 kBJavaScriptView Raw
1/*
2 * Copyright 2011 Joyent, Inc. All rights reserved.
3 *
4 * An expiring LRU cache.
5 *
6 * Usage:
7 * var Cache = require('amon-common').Cache;
8 * // size, expiry, log, name
9 * this.accountCache = new Cache( 100, 300, log, 'account');
10 * this.accountCache.set('hamish', {...});
11 * ...
12 * this.accountCache.get('hamish') // -> {...}
13 */
14
15var assert = require('assert');
16var LRU = require('lru-cache');
17
18
19/**
20 * A LRU and expiring cache.
21 *
22 * @param {number} size Max number of entries to cache.
23 * @param {number} expiry Number of seconds after which to expire entries.
24 * @param {object} log Optional. All logging is at the Trace level.
25 * @param {string} name Optional name for this cache. Just used for logging.
26 * @constructor
27 */
28function 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 * Clear cache
40 *
41 * @returns {undefined}
42 */
43Cache.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 * Get object from cache by given key
52 *
53 * @param {string} key - The cache key
54 * @returns {*} The cached value or null if not found
55 */
56Cache.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 * Set a value to cache
75 *
76 * @param {string} key - Cache key
77 * @param {*} value - The value to cache
78 * @returns {*} The given value
79 */
80Cache.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 * Delete a single entry from cache
95 *
96 * @param {string} key - The cache key
97 * @returns {undefined}
98 */
99Cache.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
107module.exports = Cache;