-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathcustom-incremental-cache-handler.mjs
89 lines (80 loc) · 2.42 KB
/
custom-incremental-cache-handler.mjs
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
// @ts-check
import {
reviveFromBase64Representation,
replaceJsonWithBase64
} from "@neshca/json-replacer-reviver";
import { IncrementalCache } from "@neshca/cache-handler";
import { WebdisKV } from "./src/lib/server/kv/webdis.server.mjs";
/** @type {{ version: number, items: Record<string, {revalidatedAt: number}>}} */
const localTagsManifest = {
version: 1,
items: {}
};
const TAGS_MANIFEST_KEY = "sharedTagsManifest";
const CACHE_HANDLER_KEY = "incrementalCache";
/**
* @typedef {typeof CACHE_HANDLER_KEY} CACHE_HANDLER_KEY
*/
const client = new WebdisKV();
IncrementalCache.onCreation(() => {
return {
useFileSystem: false, // don't read or write from the file system
cache: {
async get(key) {
try {
const result = /** @type {{ [CACHE_HANDLER_KEY]: string }} */ (
await client.get(key)
);
if (!result) {
return null;
}
// use reviveFromBase64Representation to restore binary data from Base64
return JSON.parse(
result[CACHE_HANDLER_KEY],
reviveFromBase64Representation
);
} catch (error) {
return null;
}
},
async set(key, value) {
try {
// use replaceJsonWithBase64 to store binary data in Base64 and save space
await client.set(key, {
[CACHE_HANDLER_KEY]: JSON.stringify(value, replaceJsonWithBase64)
});
} catch (error) {
// ignore because value will be written to disk
}
},
async getTagsManifest() {
try {
const remoteTagsManifest = await client.hGetAll(TAGS_MANIFEST_KEY);
if (!remoteTagsManifest) {
return localTagsManifest;
}
Object.entries(remoteTagsManifest).reduce(
(acc, [tag, revalidatedAt]) => {
acc[tag] = {
revalidatedAt: parseInt(revalidatedAt ?? "0", 10)
};
return acc;
},
localTagsManifest.items
);
return localTagsManifest;
} catch (error) {
return localTagsManifest;
}
},
async revalidateTag(tag, revalidatedAt) {
try {
await client.hSet(TAGS_MANIFEST_KEY, tag, revalidatedAt);
} catch (error) {
localTagsManifest.items[tag] = { revalidatedAt };
}
}
}
};
});
export default IncrementalCache;