Router middleware for koa. Based on find-my-way, a crazy fast http radix based router.
npm install koa-router-find-my-way --save
Note: koa-router-find-my-way@5 is based on find-my-way@5.
Old versions:
- koa-router-find-my-way@4 => find-my-way@3
- koa-router-find-my-way@3 => find-my-way@2
- koa-router-find-my-way@2 => find-my-way@1
const koaRouter = require('koa-router-find-my-way');
const app = new Koa();
const router = koaRouter();
router.get('/test/:p', async (ctx, next) => {
const { p } = ctx.params;
ctx.body = {
p,
};
await next();
});
app.use(router.routes());
app.listen(80);
All options
are passed directly to find-my-way.
Register a new route.
router
.on('GET', '/examples', async (ctx, next) => {
// a koa middleware
await next();
}, async (ctx, next) => {
// another koa middleware
ctx.body = 'Hello World!';
})
.on('DELETE', '/examples', (ctx, next) => {
// ...
})
.on(['POST', 'PUT'], '/examples', (ctx, next) => {
// ...
});
Last argument, store
is used to pass an object that you can access later inside the handler function. If needed, store can be updated.
router
.on('GET', '/examples', async (ctx, next) => {
assert.equal(ctx.store, { message: 'hello world' });
}, { message: 'hello world' });
If you want an even nicer api, you can also use the shorthand methods to declare your routes.
For each HTTP supported method, there's the shorthand method.
If you need a route that supports all methods you can use the all
api.
router
.get('/', (ctx, next) => {
ctx.body = 'Hello World!';
})
.post('/users', (ctx, next) => {
// ...
})
.put('/users/:id', (ctx, next) => {
// ...
})
.delete('/users/:id', (ctx, next) => {
// ...
})
.all('/users/:id', (ctx, next) => {
// ...
});
Returns router middleware which dispatches a route matching the request.
Deregister a route.
router.off('GET', '/example');
Empty router.
router.reset();
Return (if present) the route registered in method:path.
The path must be sanitized, all the parameters and wildcards are decoded automatically.
router.find('GET', '/example')
// => { handler: Function, params: Object, store: Object}
// => null
Prints the representation of the internal radix tree, useful for debugging.
router
.get('/test', () => {})
.get('/test/hello', () => {})
.get('/hello/world', () => {});
console.log(router.prettyPrint());
// └── /
// ├── test (GET)
// │ └── /hello (GET)
// └── hello/world (GET)