summaryrefslogtreecommitdiffstats
path: root/server/modules/apicache/memory-cache.js
blob: a91eee324e47a71607cbffcf5b9b21314ba72390 (plain)
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
function MemoryCache() {
    this.cache = {};
    this.size = 0;
}

/**
 * 
 * @param {string} key Key to store cache as
 * @param {any} value Value to store
 * @param {number} time Time to store for
 * @param {function(any, string)} timeoutCallback Callback to call in
 * case of timeout
 * @returns {Object}
 */
MemoryCache.prototype.add = function (key, value, time, timeoutCallback) {
    let old = this.cache[key];
    let instance = this;

    let entry = {
        value: value,
        expire: time + Date.now(),
        timeout: setTimeout(function () {
            instance.delete(key);
            return timeoutCallback && typeof timeoutCallback === "function" && timeoutCallback(value, key);
        }, time)
    };

    this.cache[key] = entry;
    this.size = Object.keys(this.cache).length;

    return entry;
};

/**
 * Delete a cache entry
 * @param {string} key Key to delete
 * @returns {null}
 */
MemoryCache.prototype.delete = function (key) {
    let entry = this.cache[key];

    if (entry) {
        clearTimeout(entry.timeout);
    }

    delete this.cache[key];

    this.size = Object.keys(this.cache).length;

    return null;
};

/**
 * Get value of key
 * @param {string} key 
 * @returns {Object}
 */
MemoryCache.prototype.get = function (key) {
    let entry = this.cache[key];

    return entry;
};

/**
 * Get value of cache entry
 * @param {string} key 
 * @returns {any}
 */
MemoryCache.prototype.getValue = function (key) {
    let entry = this.get(key);

    return entry && entry.value;
};

/**
 * Clear cache
 * @returns {boolean}
 */
MemoryCache.prototype.clear = function () {
    Object.keys(this.cache).forEach(function (key) {
        this.delete(key);
    }, this);

    return true;
};

module.exports = MemoryCache;