forked from lucacasonato/deno_httpcache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
79 lines (60 loc) · 2.12 KB
/
mod.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
import CachePolicy from "https://cdn.skypack.dev/http-cache-semantics?dts";
function cacheRequest(req: Request): CachePolicy.Request {
return {
url: req.url,
headers: Object.fromEntries(req.headers.entries()),
method: req.method,
};
}
export interface CachedResponse {
body: Uint8Array;
policy: CachePolicy.CachePolicyObject;
}
export interface CacheStorage {
get(url: string): Promise<CachedResponse | undefined>;
set(url: string, resp: CachedResponse): Promise<void>;
delete(url: string): Promise<void>;
close(): void;
}
export class Cache {
#storage: CacheStorage;
constructor(storage: CacheStorage) {
this.#storage = storage;
}
close() {
this.#storage.close();
}
async match(request: RequestInfo): Promise<Response | undefined> {
const req = request instanceof Request ? request : new Request(request);
const cached = await this.#storage.get(req.url);
if (cached === undefined) return Promise.resolve(undefined);
const policy = CachePolicy.fromObject(cached.policy);
const usable = policy.satisfiesWithoutRevalidation(cacheRequest(req));
if (!usable) return Promise.resolve(undefined);
const resp = new Response(cached.body, {
headers: policy.responseHeaders() as Record<string, string>,
status: cached.policy.st,
});
return Promise.resolve(resp);
}
async put(request: RequestInfo, response: Response): Promise<void> {
const req = request instanceof Request ? request : new Request(request);
response = response.clone();
const status = response.status;
const headers = Object.fromEntries(response.headers.entries());
const policy = new CachePolicy(cacheRequest(req), { status, headers }, {
shared: true,
});
if (!policy.storable()) return;
const body = await response.arrayBuffer();
await this.#storage.set(req.url, {
body: new Uint8Array(body),
policy: policy.toObject(),
});
}
async delete(request: RequestInfo): Promise<void> {
const req = request instanceof Request ? request : new Request(request);
await this.#storage.delete(req.url);
return Promise.resolve();
}
}