feat(http/unstable): add support for multiple request methods on route (#6003)

feat(http): add suppport multiple request methods on route
This commit is contained in:
LitoMore 2024-09-18 14:28:27 +08:00 committed by GitHub
parent 77eba7f042
commit e1c8d24144
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 4 deletions

View File

@ -28,11 +28,11 @@ export interface Route {
*/
pattern: URLPattern;
/**
* Request method.
* Request method. This can be a string or an array of strings.
*
* @default {"GET"}
*/
method?: string;
method?: string | string[];
/**
* Request handler.
*/
@ -61,7 +61,12 @@ export interface Route {
* {
* pattern: new URLPattern({ pathname: "/static/*" }),
* handler: (req: Request) => serveDir(req)
* }
* },
* {
* pattern: new URLPattern({ pathname: "/api" }),
* method: ["GET", "HEAD"],
* handler: (req: Request) => new Response(req.method === 'HEAD' ? null : 'ok'),
* },
* ];
*
* function defaultHandler(_req: Request) {
@ -91,7 +96,12 @@ export function route(
return (request: Request, info?: Deno.ServeHandlerInfo) => {
for (const route of routes) {
const match = route.pattern.exec(request.url);
if (match && request.method === (route.method ?? "GET")) {
if (
match &&
(Array.isArray(route.method)
? route.method.includes(request.method)
: request.method === (route.method ?? "GET"))
) {
return route.handler(request, info, match);
}
}

View File

@ -18,6 +18,12 @@ const routes: Route[] = [
method: "POST",
handler: () => new Response("Done"),
},
{
pattern: new URLPattern({ pathname: "/resource" }),
method: ["GET", "HEAD"],
handler: (request: Request) =>
new Response(request.method === "HEAD" ? null : "Ok"),
},
];
function defaultHandler(request: Request) {
@ -54,4 +60,18 @@ Deno.test("route()", async (t) => {
assertEquals(response?.status, 404);
assertEquals(await response?.text(), "/not-found");
});
await t.step("handles multiple methods", async () => {
const getMethodRequest = new Request("http://example.com/resource");
const getMethodResponse = await handler(getMethodRequest);
assertEquals(getMethodResponse?.status, 200);
assertEquals(await getMethodResponse?.text(), "Ok");
const headMethodRequest = new Request("http://example.com/resource", {
method: "HEAD",
});
const headMethodResponse = await handler(headMethodRequest);
assertEquals(headMethodResponse?.status, 200);
assertEquals(await headMethodResponse?.text(), "");
});
});