Skip to content

Instantly share code, notes, and snippets.

@umutbasal
Created January 23, 2022 12:08
Show Gist options
  • Save umutbasal/8fa20b5e643a0ddf395700ef9b8f342a to your computer and use it in GitHub Desktop.
Save umutbasal/8fa20b5e643a0ddf395700ef9b8f342a to your computer and use it in GitHub Desktop.
import { serve } from "https://deno.land/[email protected]/http/server.ts";
interface ERequest extends Request {
params: any;
}
function routes(req: ERequest): Response {
const handlers = [
{
pattern: new URLPattern({ pathname: "/books" }),
handler: getBooks,
},
{
pattern: new URLPattern({ pathname: "/books/:id" }),
handler: getBook,
},
];
return handlers.find(h => {
const match = h.pattern.exec(req.url);
req.params = match?.pathname.groups;
if (match) {
return h.handler(req);
}
})?.handler(req) ?? new Response(`Not found`);
};
function getBook(req: ERequest): Response {
return new Response(`Book ${req.params.id}`);
}
function getBooks(req: ERequest): Response {
return new Response("Books");
}
function handler(req: Request): Response {
return routes(req as ERequest);
}
console.log("Listening on http://localhost:8000");
serve(handler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment