UNPKG

1.09 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('./Cache');
7
8module.exports = class DatabaseCache extends Base {
9
10 _cache = {};
11
12 constructor (config) {
13 super({
14 table: 'cache',
15 ...config
16 });
17 this.db = this.module.getDb(this.db);
18 }
19
20 async getValue (key) {
21 const doc = await this.getQuery().and({key}).one();
22 if (doc && (!doc.expiredAt || doc.expiredAt > Date.now() / 1000)) {
23 return doc.value;
24 }
25 }
26
27 setValue (key, value, duration) {
28 const expiredAt = duration ? Math.trunc(Date.now() / 1000 + duration) : 0;
29 return this.getQuery().and({key}).upsert({key, value, expiredAt});
30 }
31
32 removeValue (key) {
33 return this.getQuery().and({key}).delete();
34 }
35
36 flushValues () {
37 return this.db.truncate(this.table);
38 }
39
40 getQuery () {
41 return (new Query).db(this.db).from(this.table);
42 }
43};
44
45const Query = require('../db/Query');
\No newline at end of file