Skip to content

jiangfengming/koa-pilot

Repository files navigation

koa-pilot

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+.

Usage

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);

Constructor

new Router([
  [method?, pattern, middleware],
  ...
])

method

String. Optional, defaults to GET. HTTP method, case-sensitive.

methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, TRACE, PURGE.

pattern

See url-router#pattern.

params defined in pattern are stored in ctx.params as a StringCaster object.

middleware

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, ...]))

Define routes

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.

router.middleware

Function. The router middleware.

app.use(router.middleware)

ctx.queries

Wraps ctx.query as a StringCaster object.

License

MIT

About

Just another Koa router

Resources

License

Stars

Watchers

Forks

Packages

No packages published