A Trie-based Koa router, based on url-router.
NOTE: This package is written in ES2020 syntax and not transpiled. It is tested only on Node.js v14+.
import Koa from 'koa';
import Router from 'koa-pilot';
const app = new Koa();
const router = new Router([
['GET', '/', ctx => ctx.body = 'hello world'],
['/user/:username', ctx => ctx.body = `hello ${ctx.params.string('username')}. code: ${ctx.queries.int('code')}`]
]);
router.get('(.*)', ctx => ctx.body = '404');
app.use(router.middleware);
app.listen(3000);
new Router([
[method?, pattern, middleware],
...
])
String.
Optional, defaults to GET
. HTTP method, case-sensitive.
methods: GET
, POST
, PUT
, DELETE
, PATCH
, HEAD
, OPTIONS
, TRACE
, PURGE
.
See url-router#pattern.
params defined in pattern
are stored in ctx.params
as a StringCaster object.
Function
. The middleware to handle the request. If you want to use multiple middleware, you can use
koa-compose:
const compose = require('koa-compose')
router.get('/foo', compose([middleware1, middleware2, ...]))
router
.add(method, path, middleware)
.get(path, middleware)
.post(path, middleware)
.put(path, middleware)
.delete(path, middleware)
.patch(path, middleware)
.head(path, middleware)
.options(path, middleware)
.trace(path, middleware)
.purge(path, middleware)
These methods return the router instance. So you could use method chaining.
Function
. The router middleware.
app.use(router.middleware)
Wraps ctx.query
as a StringCaster object.