Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/TehShrike/koa-bestest-router
Router middleware for Koa. Mutation-free, less than 100 lines
https://github.com/TehShrike/koa-bestest-router
Last synced: about 2 months ago
JSON representation
Router middleware for Koa. Mutation-free, less than 100 lines
- Host: GitHub
- URL: https://github.com/TehShrike/koa-bestest-router
- Owner: TehShrike
- Created: 2017-04-08T14:54:11.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2018-01-06T01:18:17.000Z (about 7 years ago)
- Last Synced: 2024-11-09T12:26:37.185Z (2 months ago)
- Language: JavaScript
- Homepage:
- Size: 5.86 KB
- Stars: 6
- Watchers: 4
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
- awesome-koa - koa-bestest-router - Koa 的路由器中间件。无突变(Mutation-free),少于100行 ![](https://img.shields.io/github/stars/TehShrike/koa-bestest-router.svg?style=social&label=Star) ![](https://img.shields.io/npm/dm/koa-bestest-router.svg?style=flat-square) (仓库 / 中间件)
README
# koa-bestest-router
The name's a bit of a joke, I was just amused by the existence of koa-router and koa-better-router.
When trying to track down an issue in another router, I was shocked by how much state mutation and code they were using. So I wrote this.
No mutations, not much code = easy to understand and debug. Intended for simple apps. If you want to take it a step further, consider composing koa-bestest-router instances with [`koa-mount`](https://github.com/koajs/mount).
# API
A single function. It takes a POJO map of HTTP methods to a map of routes to handler functions.
It returns a Koa middleware function.
```js
const createRouter = require('koa-bestest-router')const routerMiddleware = createRouter({
GET: {
'/pie': async (context, next) => {
context.body = 'Yay pie!'
},
'/cake/:flavor': async (context, next) => {
context.body = `I like ${context.params.flavor} cake`
}
},
POST: {
'/cake/:flavor': async (context, next) => {
someDb.addFlavor(context.params.flavor)
}
}
})koaApp.use(routerMiddleware)
```## `routerMiddleware = createRouter(routes, [options])`
`routes` is a map of HTTP methods to maps of [path-to-regexp](https://github.com/pillarjs/path-to-regexp) routes to handler functions.
Routes will be checked in a deterministic order from top to bottom, [thanks to ES2015](http://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties).
`options` is an object with only one supported property at the moment:
- `set404`: defaults to false. When true, will set `context.status = 404` when no matching routes are found for a request.
# License
[WTFPL](http://wtfpl2.com)