UNPKG

1.62 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('../base/Component');
7
8module.exports = class Cache extends Base {
9
10 constructor (config) {
11 super({
12 keyPrefix: null,
13 defaultDuration: 100, // seconds
14 serializer: null,
15 ...config
16 });
17 }
18
19 async use (key, getter, duration) {
20 let value = await this.get(key);
21 if (value === undefined) {
22 value = await getter();
23 await this.set(key, value, duration);
24 }
25 return value;
26 }
27
28 async get (key, defaults) {
29 key = this.buildKey(key);
30 const value = await this.getValue(key);
31 if (value === undefined) {
32 return defaults;
33 }
34 this.log('trace', `Get: ${key}`);
35 return this.serializer ? this.serializer.parse(value) : value;
36 }
37
38 set (key, value, duration) {
39 if (!Number.isInteger(duration)) {
40 duration = this.defaultDuration;
41 }
42 key = this.buildKey(key);
43 if (this.serializer) {
44 value = this.serializer.stringify(value);
45 }
46 this.log('trace', `Set: ${key}: Duration: ${duration}`);
47 return this.setValue(key, value, duration);
48 }
49
50 remove (key) {
51 key = this.buildKey(key);
52 return this.removeValue(key);
53 }
54
55 flush () {
56 return this.flushValues();
57 }
58
59 buildKey (key) {
60 return this.keyPrefix ? `${this.keyPrefix}${key}` : key;
61 }
62};
\No newline at end of file