import { Router } from "https://deno.land/x/acorn@0.0.5/router.ts";
A router which is specifically geared for handling RESTful type of requests and providing a straight forward API to respond to them.
A RouteHandler
is registered with the router, and when a request
matches a route the handler will be invoked. The handler will be provided
with Context
of the current request. The handler can return a
web platform
Response
instance, BodyInit
value, or any other object which will be to be
serialized to a JSON string as set as the value of the response body.
The handler context includes a property named cookies
which is an instance
of Cookies
, which provides an interface for reading request
cookies and setting cookies in the response. Cookies
supports cryptographic
signing of keys using a key ring which adheres to the KeyRing
interface, which can be passed as an option when creating the router.
KeyStack
is a key ring that implements this interface.
The route is specified using the pathname part of the
URLPattern
API,
which supports routes with wildcards (e.g. /posts/*
) and named groups (e.g.
/books/:id
) which are then provided as .params
on the context argument to
the handler.
When registering a route handler, a Deserializer
,
Serializer
, and ErrorHandler
can all be specified.
When a deserializer is specified and a request has a body, the deserializer
will be used to parse the body. This is designed to make it possible to
validate a body or hydrate an object from a request. When a serializer is
specified and the handler returns something other than a Response
or
BodyInit
, the serializer will be used to serialize the response from the
route handler, if present, otherwise
JSON.stringify()
will be used to convert the body used in the response.
Observability of the router is designed using DOM events, where there are several events which can be listened for:
"error"
- produces aRouterErrorEvent
when an error occurs when within the router. This can be used to provide a customized response for errors."listen"
- produces aRouterListenEvent
when the router has successfully started listening to requests."handled"
- produces aHandledEvent
when the router has completed handling of a request and has sent the response."notfound"
- produces aNotFoundEvent
when the router was unable to provide a response for a given request. This can be used to provide a customized response for not found events.
Example
import { Router } from "https://deno.land/x/acorn/mod.ts";
const router = new Router();
router.all("/:id", (ctx) => ({ id: ctx.params.id }));
router.listen({ port: 8080 });