This repository has been archived by the owner on Jul 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.ts
89 lines (69 loc) · 1.91 KB
/
cache.ts
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
import { hashSource } from './hash.ts';
import { debug } from './log.ts';
export type CacheMethod = 'memory' | 'disk';
export const ensureDirectory = async (path: string) => {
await Deno.mkdir(path, { recursive: true });
};
const memoryCache = new Map<string, string>();
export const cacheGet = async (
key: string,
method: CacheMethod = 'memory',
directory = '.cache',
): Promise<string | undefined> => {
// console.log('cache.get', key, method, directory);
if (method === 'memory') {
return memoryCache.get(key);
}
if (method === 'disk') {
await ensureDirectory(directory);
const path = `${directory}/${key}`;
try {
const cached = await Deno.readTextFile(path);
return cached;
} catch (_error: unknown) {
return undefined;
}
}
return undefined;
};
export const cacheSet = async (
key: string,
value: string,
method: CacheMethod = 'memory',
directory = '.cache',
): Promise<void> => {
// console.log('cache.set', key, value, method, directory);
if (method === 'memory') {
memoryCache.set(key, value);
}
if (method === 'disk') {
await ensureDirectory(directory);
const path = `${directory}/${key}`;
try {
await Deno.writeTextFile(path, value);
} catch (_error: unknown) {
return undefined;
}
}
};
export const ensureCachedFile = async (
filePath: string,
source: string,
cacheDirectoryPath: string,
cacheMethod: CacheMethod,
fn: (source: string) => Promise<string>,
) => {
debug('ensureCachedFile', filePath);
let cacheKey: string = filePath;
if (cacheMethod === 'disk') {
cacheKey = hashSource(source);
}
const cached = await cacheGet(cacheKey, cacheMethod, cacheDirectoryPath);
if (cached) {
debug('ensureCachedFile:cached', filePath);
return cached;
}
const result = await fn(source);
await cacheSet(cacheKey, result, cacheMethod, cacheDirectoryPath);
return result;
};