fix(http/unstable): make info parameter optional (#5652)

refactor(http): make `info` parameter
This commit is contained in:
Asher Gomez 2024-08-07 15:12:53 +02:00 committed by GitHub
parent ce02d496a4
commit 32ece25136
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 13 additions and 16 deletions

View File

@ -16,7 +16,7 @@
*/
export type Handler = (
request: Request,
info: Deno.ServeHandlerInfo,
info?: Deno.ServeHandlerInfo,
params?: URLPatternResult | null,
) => Response | Promise<Response>;
@ -88,10 +88,16 @@ export interface Route {
*/
export function route(
routes: Route[],
defaultHandler: Deno.ServeHandler,
): Deno.ServeHandler {
defaultHandler: (
request: Request,
info?: Deno.ServeHandlerInfo,
) => Response | Promise<Response>,
): (
request: Request,
info?: Deno.ServeHandlerInfo,
) => Response | Promise<Response> {
// TODO(iuioiua): Use `URLPatternList` once available (https://github.com/whatwg/urlpattern/pull/166)
return (request: Request, info: Deno.ServeHandlerInfo) => {
return (request: Request, info?: Deno.ServeHandlerInfo) => {
for (const route of routes) {
const match = route.pattern.exec(request.url);
if (match) return route.handler(request, info, match);

View File

@ -20,21 +20,12 @@ function defaultHandler(request: Request) {
return new Response(new URL(request.url).pathname, { status: 404 });
}
const info: Deno.ServeHandlerInfo = {
remoteAddr: {
transport: "tcp",
hostname: "example.com",
port: 80,
},
completed: Promise.resolve(),
};
Deno.test("route()", async (t) => {
const handler = route(routes, defaultHandler);
await t.step("handles static routes", async () => {
const request = new Request("http://example.com/about");
const response = await handler(request, info);
const response = await handler(request);
assertEquals(response?.status, 200);
assertEquals(await response?.text(), "/about");
});
@ -43,14 +34,14 @@ Deno.test("route()", async (t) => {
const request = new Request("http://example.com/users/123", {
method: "POST",
});
const response = await handler(request, info);
const response = await handler(request);
assertEquals(await response?.text(), "123");
assertEquals(response?.status, 200);
});
await t.step("handles default handler", async () => {
const request = new Request("http://example.com/not-found");
const response = await handler(request, info);
const response = await handler(request);
assertEquals(response?.status, 404);
assertEquals(await response?.text(), "/not-found");
});