Created
January 23, 2022 12:08
-
-
Save umutbasal/8fa20b5e643a0ddf395700ef9b8f342a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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