Skip to content

Commit

Permalink
feat(http/unstable): add support for multiple request methods on route (
Browse files Browse the repository at this point in the history
#6003)

feat(http): add suppport multiple request methods on route
  • Loading branch information
LitoMore committed Sep 18, 2024
1 parent 77eba7f commit e1c8d24
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
18 changes: 14 additions & 4 deletions http/unstable_route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
}
Expand Down
20 changes: 20 additions & 0 deletions http/unstable_route_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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(), "");
});
});

0 comments on commit e1c8d24

Please sign in to comment.