-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrap-fetch.ts
42 lines (40 loc) · 1.05 KB
/
wrap-fetch.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
import {
CacheTagStore,
ObjectCache,
provideCacheTagStore,
provideObjectCache,
provideWaitUntil,
} from "./cache";
export type CacheConfig<Env = unknown> = {
objectCache: ObjectCache | ((env: Env) => ObjectCache);
cacheTagStore: CacheTagStore | ((env: Env) => CacheTagStore);
};
export function provideCacheToFetch<Env = unknown>(
config: CacheConfig<Env>,
fetch: ExportedHandlerFetchHandler<Env>
) {
const wrappedFetch: ExportedHandlerFetchHandler<Env> = async (
request,
env,
ctx
) => {
const objectCache =
typeof config.objectCache === "function"
? config.objectCache(env)
: config.objectCache;
const cacheTagStore =
typeof config.cacheTagStore === "function"
? config.cacheTagStore(env)
: config.cacheTagStore;
return provideWaitUntil(
(p) => ctx.waitUntil(p),
() =>
provideObjectCache(objectCache, () =>
provideCacheTagStore(cacheTagStore, async () =>
fetch(request, env, ctx)
)
)
);
};
return wrappedFetch;
}