-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate-request-handler.ts
More file actions
386 lines (356 loc) · 11.2 KB
/
Copy pathcreate-request-handler.ts
File metadata and controls
386 lines (356 loc) · 11.2 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import { ZodError, z } from "zod/v4";
import {
INVALIDATIONS_ROUTE,
OPENAPI_ROUTE,
SESSION_COOKIE_NAME,
} from "../shared/constants.js";
import { HttpError } from "../shared/http-error.js";
import type { MaybePromise } from "../shared/maybe-promise.js";
import type { Path as BasePath } from "../shared/path.js";
import type { BaseRoute } from "../shared/route.js";
import { CookieStore } from "./cookie-store.js";
import type { ApiDefinition } from "./define-api.js";
import type { Handler } from "./handler.js";
import type { TRequest } from "./t-request.js";
import type { Cache } from "./cache.js";
import { generateOpenAPISchema } from "./openapi.js";
import { streamRevalidatedTags } from "./revalidation-stream.js";
interface Options {
/** the root path for all API routes */
basePath?: string;
hooks?: {
error?: (error: unknown) => MaybePromise<void>;
};
/** the default maximum time-to-live (TTL) for cached responses */
defaultTTL?: number;
}
const DEFAULT_TTL = 60 * 60 * 24 * 14;
const authUsed = Symbol("TApi.authUsed");
const headersSchema = z
.tuple([z.string(), z.string()])
.array()
.optional()
.nullable();
export function createRequestHandler(
api: ApiDefinition<Record<BasePath, MaybePromise<BaseRoute>>>,
options: Options = {},
) {
const errorHook =
options.hooks?.error ??
((error) => {
console.error(error);
return error;
});
const basePath = options.basePath ?? "";
const routes: { pattern: RegExp; route: MaybePromise<BaseRoute> }[] = [];
for (const [path, route] of Object.entries(api.routes)) {
const pattern = compilePathRegex(basePath + path);
routes.push({ pattern, route });
}
let openapiJson: string | undefined;
return async (req: Request) => {
const url = new URL(req.url);
if (url.pathname === `${basePath}${INVALIDATIONS_ROUTE}`) {
return streamRevalidatedTags({
cache: api.cache,
});
}
if (api.openapi && url.pathname === `${basePath}${OPENAPI_ROUTE}`) {
if (!openapiJson) {
const spec = await generateOpenAPISchema(api, { info: api.openapi });
openapiJson = JSON.stringify(spec);
}
return new Response(openapiJson, {
headers: { "Content-Type": "application/json" },
});
}
for (const { pattern, route: routePromise } of routes) {
const match = url.pathname.match(pattern);
const route = await routePromise;
if (match) {
const params = match.groups || {};
switch (req.method) {
case "HEAD":
case "GET": {
try {
// get matching cache entry
const cached = await api.cache?.get(req.url);
if (cached) {
// serve from cache
const body =
req.method === "HEAD"
? null
: new ReadableStream({
start(controller) {
controller.enqueue(cached.attachment);
controller.close();
},
});
const headers = await headersSchema.parseAsync(cached.data);
return new Response(body, {
headers: headers ?? undefined,
});
}
} catch (error) {
// caches errors while retrieving from cache
errorHook(error);
}
const handler = route[req.method];
if (!handler) return new Response("Not Found", { status: 404 });
try {
// execute handler, serve fresh response
const treq = await prepareRequestWithoutBody(
handler,
url,
params,
req,
api.cache,
);
const res = await executeHandler(handler, treq);
if (res.cache) {
if ((treq as any)[authUsed] !== true) {
// cache fresh response according to cache options
try {
const cloned = res.clone();
api.cache
?.set({
key: req.url,
data: Array.from(res.headers.entries()),
attachment: new Uint8Array(await cloned.arrayBuffer()),
ttl: res.cache.ttl ?? options.defaultTTL ?? DEFAULT_TTL,
tags: res.cache.tags ?? [],
})
// catches errors while caching if cache.set is async (redis cache)
.catch(errorHook);
} catch (error) {
// catches errors while caching if cache.set is sync (in-memory cache)
errorHook(error);
}
}
}
return res;
} catch (error) {
// catches errors while actually handling the request
await errorHook(error);
return handleError(error);
}
}
case "DELETE": {
const handler = route[req.method];
if (!handler) return new Response("Not Found", { status: 404 });
try {
const treq = await prepareRequestWithoutBody(
handler,
url,
params,
req,
api.cache,
);
const res = await executeHandler(handler, treq);
if (res.cache?.tags) {
try {
const clientId = await treq
.cookies()
.get(SESSION_COOKIE_NAME);
api.cache
?.delete(
res.cache.tags,
clientId ? { clientId: clientId.value } : undefined,
)
.catch(errorHook);
} catch (error) {
errorHook(error);
}
}
return res;
} catch (error) {
await errorHook(error);
return handleError(error);
}
}
case "POST":
case "PUT":
case "PATCH": {
const handler = route[req.method];
if (!handler)
return new Response("Not Found", {
status: 404,
statusText: "Not Found",
});
try {
const treq = await prepareRequestWithBody(
handler,
url,
params,
req,
api.cache,
);
const res = await executeHandler(handler, treq);
if (res.cache?.tags) {
try {
const clientId = await treq
.cookies()
.get(SESSION_COOKIE_NAME);
api.cache
?.delete(
res.cache.tags,
clientId ? { clientId: clientId.value } : undefined,
)
.catch(errorHook);
} catch (error) {
errorHook(error);
}
}
return res;
} catch (error) {
await errorHook(error);
return handleError(error);
}
}
default:
return new Response("Not Found", {
status: 404,
statusText: "Not Found",
});
}
}
}
return new Response("Not Found", { status: 404, statusText: "Not Found" });
};
}
export function compilePathRegex(path: string): RegExp {
// Handle wildcards: *name captures as named group, * catches all without capturing
const pattern = path
.replaceAll(/\*(\w+)/g, "(?<$1>.+)") // *name -> named capture group
.replaceAll(/\*/g, ".+") // * -> match everything including /
.replaceAll(/:(\w+)/g, "(?<$1>[^\\/]+)"); // :param -> named capture group
return new RegExp(`^${pattern}$`);
}
async function prepareRequestWithoutBody<TBody = never>(
handler: Handler<any, any, any, TBody>,
url: URL,
params: Record<string, string>,
req: Request,
cache: Cache,
) {
const treq = req as TRequest<any, any, any, TBody>;
treq.params = () => {
const decodedParams = Object.fromEntries(
Object.entries(params).map(([key, value]) => [
key,
decodeURIComponent(value),
]),
);
if (handler.schema.params) {
const schema = z.object(handler.schema.params);
return schema.parse(decodedParams);
}
treq.params = () => decodedParams;
return decodedParams;
};
treq.query = () => {
const params = collectData(url.searchParams.entries());
if (handler.schema.query) {
const schema = z.object(handler.schema.query);
return schema.parse(params);
}
treq.query = () => params;
return params;
};
treq.cookies = () => {
const cookieStore = new CookieStore(req);
treq.cookies = () => cookieStore;
return cookieStore;
};
treq.invalidate = async (tags: string[]) => {
const clientId = await treq.cookies().get(SESSION_COOKIE_NAME);
cache.delete(tags, clientId ? { clientId: clientId.value } : undefined);
};
const auth = await handler.schema.authorize(
treq as TRequest<never, any, any, never>,
);
if (!auth) {
throw new HttpError(401, "Unauthorized");
}
treq.auth = () => {
(treq as any)[authUsed] = true;
return auth;
};
return treq;
}
async function prepareRequestWithBody(
handler: Handler<any, any, any, unknown>,
url: URL,
params: Record<string, string>,
req: Request,
cache: Cache,
) {
const treq = await prepareRequestWithoutBody(
handler,
url,
params,
req,
cache,
);
if (handler.schema.body) {
treq.data = async () => handler.schema.body?.parseAsync(await req.json());
} else {
treq.data = () => {
console.error(
"Unexpected call to TRequest.data() method: no body parser specified",
);
throw new HttpError(500, "Internal Server Error");
};
}
return treq;
}
function collectData(input: Iterable<[string, any]>) {
const params: Record<string, string | string[]> = {};
for (const [key, value] of input) {
if (params[key]) {
if (Array.isArray(params[key])) {
params[key].push(value);
} else {
params[key] = [params[key], value];
}
} else {
params[key] = value;
}
}
return params;
}
export async function executeHandler<Body>(
handler: Handler<any, any, any, Body>,
req: TRequest<any, any, any, Body>,
) {
const res = await handler.handler(req);
if (handler.schema.response) {
await handler.schema.response.parseAsync(res.data);
}
return res;
}
function handleError(error: unknown) {
if (error instanceof ZodError) {
return Response.json(error.issues, {
status: 400,
headers: {
"Content-Type": "application/json+zodissues",
},
});
}
if (error instanceof HttpError) {
return Response.json(
{
message: error.message,
data: error.data,
},
{
status: error.status,
headers: {
"Content-Type": "application/json+httperror",
},
},
);
}
return new Response("Internal Server Error", { status: 500 });
}