diff --git a/deps.ts b/deps.ts index 887fcc9..8feda56 100644 --- a/deps.ts +++ b/deps.ts @@ -6,3 +6,4 @@ export { } from "https://deno.land/std@0.87.0/testing/asserts.ts"; export { readLines } from "https://deno.land/std@0.87.0/io/bufio.ts"; export { Application, Router } from "https://deno.land/x/oak/mod.ts"; +export type { RouterContext } from "https://deno.land/x/oak/mod.ts"; diff --git a/server.ts b/server.ts index 378d2e8..0a08e01 100644 --- a/server.ts +++ b/server.ts @@ -1,29 +1,41 @@ -import { Application, Router } from "./deps.ts"; +import { Application, Router, RouterContext } from "./deps.ts"; import { ID, sayHello, sayRandomHello } from "./src/index.ts"; const port = 8000; -const router = new Router(); +const htmlBody = (content: string) => + `
${content}
`; -router.get("/", (ctx: any) => { - ctx.response.body = JSON.stringify(sayRandomHello()); -}).get<{ id: string }>("/:id", (ctx: any) => { - try { - const value = ctx.params.id; - const id = new ID(value); - ctx.response.body = JSON.stringify(sayHello(id)); - } catch (error) { - console.error(error); - ctx.response.body = error.message; - } -}); +type AppOpts = { port: number }; +const get_application = ({ port }: AppOpts): Application => { + const router = new Router(); -const app = new Application(); -app.use(router.routes()); + router.get("/", (ctx: RouterContext) => { + ctx.response.body = htmlBody(JSON.stringify(sayRandomHello(), null, 2)); + }).get("/:id", (ctx: RouterContext) => { + try { + const value = ctx.params.id; + if (!!value) { + const id = new ID(parseInt(value, 10)); + ctx.response.body = htmlBody(JSON.stringify(sayHello(id), null, 2)); + } + } catch (error) { + console.error(error); + ctx.response.body = error.message; + } + }); -app.addEventListener("listen", ({ port }: any) => { - console.log(`Server listening on http://localhost:${port}/`); -}); + const app = new Application(); + + app.use(router.routes()); + + app.addEventListener("listen", ({ port }) => { + console.log(`Server listening on http://localhost:${port}/`); + }); + return app; +}; + +const app = get_application({ port }); await app.listen({ port }); console.log(`Finished`);