Open History to see the last commit
1import z from "zod";
2
3type Pathname = string;
4
5type ResponseData = {
6 contentType: "application/json" | "text/plain";
7 status: number;
8 body?: any;
9};
10
11const methodShema = z.enum(["GET", "PATCH", "POST", "DELETE"]);
12
13type Method = z.infer<typeof methodShema>;
14
15export type APIRouteHandler = Partial<
16 Record<Method, (payload: { request: Request }) => Promise<Response>>
17>;
18
19export type APIType = Record<Pathname, APIRouteHandler>;
20
21export const requestSchema = z.object({
22 href: z.url(),
23 method: methodShema,
24 requestBody: z.any().optional(),
25});
26
27export type RequestData = z.infer<typeof requestSchema>;
28
29export function json(
30 body: any,
31 opts?: {
32 status?: number;
33 },
34) {
35 const res = new Response(JSON.stringify(body), {
36 headers: {
37 "Content-Type": "application/json",
38 },
39 status: 200,
40 ...opts,
41 });
42 return res;
43}
44
45/**
46 `Response` objects can't transferred via postMessage
47 (because they can't be cloned), so we need to reconstruct
48 and deconstruct them in the main thread.
49 */
50export function constructRequestForHandler(requestData: RequestData): {
51 request: Request;
52} {
53 return {
54 request: new Request(requestData.href, {
55 method: requestData.method,
56 headers: {
57 "Content-Type": "application/json",
58 },
59 ...("requestBody" in requestData
60 ? {
61 body: requestData.requestBody
62 ? JSON.stringify(requestData.requestBody)
63 : undefined,
64 }
65 : {}),
66 }),
67 };
68}
69
70export async function deconstructResponseFromHandler(
71 response: Response,
72): Promise<ResponseData> {
73 const contentType = response.headers?.get("Content-Type") || "";
74 let body: any = null;
75 const clone = response.clone();
76
77 try {
78 if (contentType.includes("application/json")) {
79 // Clone request to read the body
80 body = await clone.json();
81 } else {
82 body = await clone.text();
83 }
84 } catch (e) {
85 console.error("Error reading response body:", e);
86 throw e;
87 }
88
89 return {
90 contentType: contentType.includes("application/json")
91 ? "application/json"
92 : "text/plain",
93 body,
94 status: response.status,
95 } satisfies ResponseData;
96}