mirror of
https://github.com/denoland/std.git
synced 2024-11-22 04:59:05 +00:00
fix(http/unstable): make info
parameter optional (#5652)
refactor(http): make `info` parameter
This commit is contained in:
parent
ce02d496a4
commit
32ece25136
@ -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);
|
||||
|
@ -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");
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user