1 |
|
2 | import type { Temporal } from 'temporal-spec';
|
3 | import type { Awaitable } from "./utils/common-types.js";
|
4 | import type { Context } from "./index.js";
|
5 |
|
6 | import { format, CacheControl } from '@tusbar/cache-control'
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export type CacheOptions = {
|
16 | [K in keyof CacheControl]: CacheControl[K] extends (number | null | undefined)
|
17 | ? number | Temporal.Duration | null
|
18 | : CacheControl[K]
|
19 | }
|
20 |
|
21 | const SECOND = { unit: 'second', relativeTo: '1970-01-01' } as Temporal.DurationTotalOf;
|
22 | const isDuration = (x?: unknown): x is Temporal.Duration => (<any>x)?.[Symbol.toStringTag] === 'Temporal.Duration'
|
23 |
|
24 | export const caching = (options: CacheOptions = {}) => async <X extends Context>(ax: Awaitable<X>) => {
|
25 | const x = await ax;
|
26 | const opts: CacheControl = Object.fromEntries(
|
27 | Object.entries(options).map(([k, v]) => [k, isDuration(v) ? v.total(SECOND) : v])
|
28 | );
|
29 | x.effects.push(res => res.headers.set('Cache-Control', format(opts)));
|
30 | return x;
|
31 | }
|