-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathcache.js
105 lines (91 loc) · 2.35 KB
/
cache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
import { writeJson, readJson, writeFile, readFile } from './file.js';
function isAsync(fn) {
return fn[Symbol.toStringTag] === 'AsyncFunction';
}
export default class Cache {
constructor(dir) {
this.dir = dir || this.computeCacheDir(os.tmpdir());
this.originals = {};
this.disabled = true;
}
computeCacheDir(base) {
return path.join(base, 'ncu', 'cache');
}
disable() {
this.disabled = true;
}
enable() {
this.disabled = false;
}
getFilename(key, ext) {
return path.join(this.dir, key) + ext;
}
has(key, ext) {
if (this.disabled) {
return false;
}
return fs.existsSync(this.getFilename(key, ext));
}
get(key, ext) {
if (!this.has(key, ext)) {
return undefined;
}
if (ext === '.json') {
return readJson(this.getFilename(key, ext));
} else {
return readFile(this.getFilename(key, ext));
}
}
write(key, ext, content) {
if (this.disabled) {
return;
}
const filename = this.getFilename(key, ext);
if (ext === '.json') {
return writeJson(filename, content);
} else {
return writeFile(filename, content);
}
}
wrapAsync(original, identity) {
const cache = this;
return async function(...args) {
const { key, ext } = identity.call(this, ...args);
const cached = cache.get(key, ext);
if (cached) {
return cached;
}
const result = await original.call(this, ...args);
cache.write(key, ext, result);
return result;
};
}
wrapNormal(original, identity) {
const cache = this;
return function(...args) {
const { key, ext } = identity.call(this, ...args);
const cached = cache.get(key, ext);
if (cached) {
return cached;
}
const result = original.call(this, ...args);
cache.write(key, ext, result);
return result;
};
}
wrap(Class, identities) {
for (const method of Object.keys(identities)) {
const original = Class.prototype[method];
const identity = identities[method];
this.originals[method] = original;
if (isAsync(original)) {
Class.prototype[method] = this.wrapAsync(original, identity);
} else {
Class.prototype[method] = this.wrapNormal(original, identity);
}
}
}
}