-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcache.js
More file actions
37 lines (31 loc) · 1.05 KB
/
cache.js
File metadata and controls
37 lines (31 loc) · 1.05 KB
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
import path from 'path';
import { mkdirp } from 'mkdirp';
import { readJsonFile, writeJsonFile } from './data';
import { getLocalStoragePath } from '../clients/cli-paths';
async function getCacheFilePath(key) {
const cacheDir = path.join(await getLocalStoragePath(), 'cache');
await mkdirp(cacheDir);
return path.join(
cacheDir,
encodeURIComponent(typeof key === 'string' ? key : JSON.stringify(key)),
);
}
export async function getValue(key) {
const cached = (await readJsonFile(await getCacheFilePath(key))) || {};
if (!cached.expiration || cached.expiration > new Date().getTime()) {
return cached.value;
}
return null;
}
export async function setValue(key, value, expirationSeconds) {
const expiration = expirationSeconds
? new Date().getTime() + expirationSeconds * 1000
: null;
await writeJsonFile({ expiration, value }, await getCacheFilePath(key));
return value;
}
export async function get(key, expirationSeconds, func) {
return (
(await getValue(key)) || setValue(key, await func(), expirationSeconds)
);
}