-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
45 lines (41 loc) · 1.22 KB
/
index.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
const HEADERS = { headers: { 'content-type': 'text/html;charset=UTF-8' } };
export const html = String.raw;
export const view = (...domArgs: string[]) =>
new Response(domArgs.join('\n'), HEADERS);
export const redirect = (url: string, status = 303) =>
new Response(null, { status, headers: { 'HX-Redirect': url } });
export type LayoutFunction<Env = any, Params extends string = any> = ({
children,
request,
params,
env,
}: {
children: string;
request?: Request;
params?: Params;
env?: Env;
}) => string | Promise<string>;
export const applyLayout =
(layout: LayoutFunction, isRoot: boolean): PagesFunction =>
async ({ request, env, params, next }) => {
const url = new URL(request.url);
const method = request.method;
if (
url.pathname.match(/\.[^/]+$/) ||
method !== 'GET' ||
url.pathname.match(/_[^/]+$/) ||
(isRoot && request.headers.get('HX-Boosted') === 'true')
) {
return next();
}
const response = await next();
const children = await response.text();
if (response.ok) {
return new Response(
await layout({ children, request, params, env }),
response
);
} else {
return new Response('NOT FOUND', response);
}
};