-
Notifications
You must be signed in to change notification settings - Fork 0
/
script_cache.ts
43 lines (37 loc) · 1.07 KB
/
script_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
import { createHash } from "https://deno.land/std@0.100.0/hash/mod.ts";
import { ensureDir } from "https://deno.land/std@0.100.0/fs/ensure_dir.ts";
import { join } from "https://deno.land/std@0.100.0/path/mod.ts";
import { Script } from "./types.ts";
const HASH_ALGORITHM = "sha256";
export class ScriptCache {
#root: string;
constructor(cacheRoot: string) {
this.#root = cacheRoot;
}
async ensureCacheDir(): Promise<void> {
await ensureDir(this.#root);
}
#path(url: string) {
const hash = createHash(HASH_ALGORITHM);
hash.update(url);
const key = hash.toString();
return join(this.#root, key);
}
async get(url: string): Promise<Script | null> {
let json: string;
try {
json = await Deno.readTextFile(this.#path(url));
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
// Cache missed
return null;
}
throw e;
}
// Cache hit
return JSON.parse(json) as Script;
}
async set(script: Script) {
await Deno.writeTextFile(this.#path(script.url), JSON.stringify(script));
}
}