1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('../base/Component');
|
7 |
|
8 | module.exports = class Cache extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | keyPrefix: null,
|
13 | defaultDuration: 100,
|
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 | removeValue () {
|
56 |
|
57 | }
|
58 |
|
59 | flush () {
|
60 | return this.flushValues();
|
61 | }
|
62 |
|
63 | buildKey (key) {
|
64 | return this.keyPrefix ? `${this.keyPrefix}${key}` : key;
|
65 | }
|
66 | }; |
\ | No newline at end of file |