1 | const lru = require('./lru-cache');
|
2 | const debugLogger = require('debug');
|
3 | const debugNamespace = Symbol('debugNamespace');
|
4 | const debug = Symbol('debug');
|
5 |
|
6 | module.exports = class ControllerCache {
|
7 |
|
8 | constructor (redisClient, controller = 'UNDEFINED-CONTROLLER!', action = 'UNDEFINED-ACTION', options = {}) {
|
9 | this.client = redisClient;
|
10 | this.controller = controller;
|
11 | this.namespace = `${controller}#${action}`;
|
12 | this.setOptions(options);
|
13 | this.cache = lru(this.client, this.options);
|
14 | this[debugNamespace] = debugLogger('glad');
|
15 | this[debug]('Created ControllerCache Instance');
|
16 | }
|
17 |
|
18 | [debug] (name) {
|
19 | this[debugNamespace]("ControllerCache %s", name);
|
20 | }
|
21 |
|
22 | setOptions (opts, rebuild) {
|
23 | let { strategy, namespace } = opts;
|
24 | if (strategy === 'LRU') {
|
25 | opts.score = () => new Date().getTime();
|
26 | opts.increment = false;
|
27 | } else if (strategy === 'LFU') {
|
28 | opts.score = () => 1;
|
29 | opts.increment = true;
|
30 | }
|
31 |
|
32 | opts.namespace = this.namespace;
|
33 |
|
34 | if (namespace && opts.namespace !== namespace) {
|
35 | opts.namespace += `-${namespace}`;
|
36 | this.namespace = opts.namespace;
|
37 | }
|
38 |
|
39 | this.options = Object.assign({
|
40 | score: () => new Date().getTime(),
|
41 | increment: false,
|
42 | max : 3
|
43 | }, opts);
|
44 |
|
45 | if (rebuild) {
|
46 | this.cache = lru(this.client, this.options);
|
47 | }
|
48 |
|
49 | }
|
50 |
|
51 | cachedVersion (req) {
|
52 | this[debug]('Cached Version');
|
53 | return this.cache.get(req.url).then(json => json || false);
|
54 | }
|
55 |
|
56 | }
|