|
| 1 | +// Copyright 2022 the oak authors. All rights reserved. MIT License. |
| 2 | + |
| 3 | +/** Contains initialization and setup functionality. |
| 4 | + * |
| 5 | + * @module |
| 6 | + */ |
| 7 | + |
| 8 | +import { Router } from "acorn"; |
| 9 | +import { type Configuration as TwindConfig, setup } from "twind"; |
| 10 | +import { type KeyRing } from "oak_commons/types"; |
| 11 | + |
| 12 | +import { sheet } from "./handlers.ts"; |
| 13 | + |
| 14 | +export interface StartOptions extends TwindConfig { |
| 15 | + /** A key ring which will be used for signing and validating cookies. */ |
| 16 | + keys?: KeyRing; |
| 17 | + /** When providing internal responses, like on unhandled errors, prefer JSON |
| 18 | + * responses to HTML responses. When set to `false` HTML will be preferred |
| 19 | + * when responding, but content type negotiation will still be respected. |
| 20 | + * Defaults to `true`. */ |
| 21 | + preferJson?: boolean; |
| 22 | + /** When `true` skip setting up default logging on the router. */ |
| 23 | + quiet?: boolean; |
| 24 | +} |
| 25 | + |
| 26 | +/** Initialize the environment optionally using the provided options, returning |
| 27 | + * an instance of {@linkcode Router}. |
| 28 | + * |
| 29 | + * ### Example |
| 30 | + * |
| 31 | + * ```ts |
| 32 | + * import { init, render } from "https://deno.land/x/nat/mod.ts"; |
| 33 | + * import { App } from "./App.tsx"; |
| 34 | + * |
| 35 | + * const router = init(); |
| 36 | + * router.get("/", render(<App />)); |
| 37 | + * |
| 38 | + * router.listen(); |
| 39 | + * ``` |
| 40 | + */ |
| 41 | +export function init(options: StartOptions = {}): Router { |
| 42 | + options.sheet = sheet; |
| 43 | + setup(options); |
| 44 | + const router = new Router(options); |
| 45 | + if (!options.quiet) { |
| 46 | + router.addEventListener( |
| 47 | + "listen", |
| 48 | + ({ secure, hostname, port }) => |
| 49 | + console.log( |
| 50 | + `%cListening: %c${ |
| 51 | + secure ? "https://" : "http://" |
| 52 | + }${hostname}:${port}`, |
| 53 | + "color:green;font-weight:bold;", |
| 54 | + "color:yellow", |
| 55 | + ), |
| 56 | + ); |
| 57 | + router.addEventListener( |
| 58 | + "handled", |
| 59 | + ( |
| 60 | + { |
| 61 | + response: { status }, |
| 62 | + route, |
| 63 | + request: { url, method }, |
| 64 | + measure: { duration }, |
| 65 | + }, |
| 66 | + ) => { |
| 67 | + const responseColor = status < 400 |
| 68 | + ? "color:green" |
| 69 | + : status < 500 |
| 70 | + ? "color:yellow" |
| 71 | + : "color:red"; |
| 72 | + let path = route?.route; |
| 73 | + if (!path) { |
| 74 | + try { |
| 75 | + path = new URL(url).pathname; |
| 76 | + } catch { |
| 77 | + // just swallow errors here |
| 78 | + } |
| 79 | + } |
| 80 | + console.log( |
| 81 | + `%c${method} ${path} - [${status}] ${duration.toFixed(2)}ms`, |
| 82 | + responseColor, |
| 83 | + ); |
| 84 | + }, |
| 85 | + ); |
| 86 | + } |
| 87 | + return router; |
| 88 | +} |
0 commit comments