1 | "use strict";
|
2 |
|
3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4 |
|
5 | exports.__esModule = true;
|
6 | exports.default = void 0;
|
7 |
|
8 | var _cacheManager = _interopRequireDefault(require("cache-manager"));
|
9 |
|
10 | var _fsExtra = _interopRequireDefault(require("fs-extra"));
|
11 |
|
12 | var _cacheManagerFsHash = _interopRequireDefault(require("cache-manager-fs-hash"));
|
13 |
|
14 | var _path = _interopRequireDefault(require("path"));
|
15 |
|
16 | const MAX_CACHE_SIZE = 250;
|
17 | const TTL = Number.MAX_SAFE_INTEGER;
|
18 |
|
19 | class Cache {
|
20 | constructor({
|
21 | name = `db`,
|
22 | store = _cacheManagerFsHash.default
|
23 | } = {}) {
|
24 | this.name = name;
|
25 | this.store = store;
|
26 | }
|
27 |
|
28 | get directory() {
|
29 | return _path.default.join(process.cwd(), `.cache/caches/${this.name}`);
|
30 | }
|
31 |
|
32 | init() {
|
33 | _fsExtra.default.ensureDirSync(this.directory);
|
34 |
|
35 | const configs = [{
|
36 | store: `memory`,
|
37 | max: MAX_CACHE_SIZE,
|
38 | ttl: TTL
|
39 | }, {
|
40 | store: this.store,
|
41 | ttl: TTL,
|
42 | options: {
|
43 | path: this.directory,
|
44 | ttl: TTL
|
45 | }
|
46 | }];
|
47 | const caches = configs.map(cache => _cacheManager.default.caching(cache));
|
48 | this.cache = _cacheManager.default.multiCaching(caches);
|
49 | return this;
|
50 | }
|
51 |
|
52 | get(key) {
|
53 | return new Promise(resolve => {
|
54 | if (!this.cache) {
|
55 | throw new Error(`Cache wasn't initialised yet, please run the init method first`);
|
56 | }
|
57 |
|
58 | this.cache.get(key, (err, res) => {
|
59 | resolve(err ? undefined : res);
|
60 | });
|
61 | });
|
62 | }
|
63 |
|
64 | set(key, value, args = {
|
65 | ttl: TTL
|
66 | }) {
|
67 | return new Promise(resolve => {
|
68 | if (!this.cache) {
|
69 | throw new Error(`Cache wasn't initialised yet, please run the init method first`);
|
70 | }
|
71 |
|
72 | this.cache.set(key, value, args, err => {
|
73 | resolve(err ? undefined : value);
|
74 | });
|
75 | });
|
76 | }
|
77 |
|
78 | }
|
79 |
|
80 | exports.default = Cache;
|
81 |
|
\ | No newline at end of file |