forked from lerna/lerna-changelog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApiDataCache.js
44 lines (37 loc) · 951 Bytes
/
ApiDataCache.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
import fs from "fs";
import path from "path";
import mkdirp from "mkdirp";
import ConfigurationError from "./ConfigurationError";
export default class ApiDataCache {
constructor(host, { rootPath, cacheDir }) {
this.host = host;
const dir = this.dir = cacheDir && path.join(rootPath, cacheDir, host);
if (dir) {
try {
mkdirp.sync(dir);
} catch (e) {
throw new ConfigurationError(
`Can't use cacheDir "${cacheDir}" (${e.message})`
);
}
}
}
get(type, key) {
if (!this.dir)
return;
try {
return fs.readFileSync(this.fn(type, key), "utf-8");
} catch (e) {}
}
set(type, key, data) {
if (!this.dir)
return;
return fs.writeFileSync(this.fn(type, key), data);
}
fn(type, key) {
const dir = path.join(this.dir, type);
// Ensure the directory for this type is there.
mkdirp.sync(dir);
return path.join(dir, key);
}
}