• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

tunnckoCore/koa-better-router: Stable and lovely router for `koa`, using `path-m ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

tunnckoCore/koa-better-router

开源软件地址:

https://github.com/tunnckoCore/koa-better-router

开源编程语言:

JavaScript 100.0%

开源软件介绍:

koa-better-router NPM version NPM monthly downloads npm total downloads

Stable and lovely router for koa, using path-match. Foundation for building powerful, flexible and RESTful APIs easily.

standard code style linux build status coverage status dependency status

You may also be interested in koa-rest-router. It uses this router for creating powerful, flexible and RESTful APIs for enterprise easily!

Highlights

  • production: ready for and used in
  • foundation: very simple core for building more powerful routers such as koa-rest-router
  • composability: group multiple routes and multiple routers - see .groupRoutes and .addRoutes
  • flexibility: multiple prefixes on same router
  • compatibility: accepts both old and modern middlewares without deprecation messages
  • powerful: multiple routers on same koa app - even can combine multiple routers
  • light: not poluting your router instance and app - see .loadMethods
  • smart: does only what you say it to do
  • small: very small on dependencies - curated and only most needed
  • backward compatible: works on koa v1 - use .legacyMiddleware
  • maintainability: very small, beautiful, maintainable and commented codebase
  • stability: strict semantic versioning and very well documented
  • tested: very well tested with 100% coverage
  • lovely: ~500 downloads for the first 2 days
  • open: love PRs for features, issues and recipes - Contribute a recipe?

Table of Contents

(TOC generated by verb using markdown-toc)

Install

Install with npm

$ npm install koa-better-router --save

or install using yarn

$ yarn add koa-better-router

Usage

For more use-cases see the tests

let router = require('koa-better-router')().loadMethods()

// or

let Router = require('koa-better-router')
let router = Router() // or new Router(), no matter

API

KoaBetterRouter

Initialize KoaBetterRouter with optional options which are directly passed to path-match and so to path-to-regexp too. In addition we have two more - prefix and notFound.

Params

  • [options] {Object}: options passed to path-match/path-to-regexp directly
  • [options.notFound] {Function}: if passed, called with ctx, next when route not found

Example

let Router = require('koa-better-router')
let router = Router().loadMethods()

router.get('/', (ctx, next) => {
  ctx.body = `Hello world! Prefix: ${ctx.route.prefix}`
  return next()
})

// can use generator middlewares
router.get('/foobar', function * (next) {
  this.body = `Foo Bar Baz! ${this.route.prefix}`
  yield next
})

let api = Router({ prefix: '/api' })

// add `router`'s routes to api router
api.extend(router)

// The server
let Koa = require('koa') // Koa v2
let app = new Koa()

app.use(router.middleware())
app.use(api.middleware())

app.listen(4444, () => {
  console.log('Try out /, /foobar, /api/foobar and /api')
})

.loadMethods

Load the HTTP verbs as methods on instance. If you not "load" them you can just use .addRoute method. If you "load" them, you will have method for each item on methods array - such as .get, .post, .put etc.

  • returns {KoaBetterRouter} this: instance for chaining

Example

let router = require('koa-better-router')()

// all are `undefined` if you
// don't `.loadMethods` them
console.log(router.get)
console.log(router.post)
console.log(router.put)
console.log(router.del)
console.log(router.addRoute) // => function
console.log(router.middleware) // => function
console.log(router.legacyMiddleware) // => function

router.loadMethods()

console.log(router.get)  // => function
console.log(router.post) // => function
console.log(router.put)  // => function
console.log(router.del)  // => function
console.log(router.addRoute) // => function
console.log(router.middleware) // => function
console.log(router.legacyMiddleware) // => function

.createRoute

Just creates "Route Object" without adding it to this.routes array, used by .addRoute method.

Params

  • <method> {String}: http verb or 'GET /users'
  • [route] {String|Function}: for what ctx.path handler to be called
  • ...fns {Function}: can be array or single function, any number of arguments after route can be given too
  • returns {Object}: plain route object with useful properties

Example

let router = require('koa-better-router')({ prefix: '/api' })
let route = router.createRoute('GET', '/users', [
  function (ctx, next) {},
  function (ctx, next) {},
  function (ctx, next) {},
])

console.log(route)
// => {
//   prefix: '/api',
//   route: '/users',
//   pathname: '/users',
//   path: '/api/users',
//   match: matcher function against `route.path`
//   method: 'GET',
//   middlewares: array of middlewares for this route
// }

console.log(route.match('/foobar'))    // => false
console.log(route.match('/users'))     // => false
console.log(route.match('/api/users')) // => true
console.log(route.middlewares.length)  // => 3

.addRoute

Powerful method to add route if you don't want to populate you router instance with dozens of methods. The method can be just HTTP verb or method plus route something like 'GET /users'. Both modern and generators middlewares can be given too, and can be combined too. Adds routes to this.routes array.

Params

  • <method> {String}: http verb or 'GET /users'
  • [route] {String|Function}: for what ctx.path handler to be called
  • ...fns {Function}: can be array or single function, any number of arguments after route can be given too
  • returns {KoaBetterRouter} this: instance for chaining

Example

let router = require('koa-better-router')()

// any number of middlewares can be given
// both modern and generator middlewares will work
router.addRoute('GET /users',
  (ctx, next) => {
    ctx.body = `first ${ctx.route.path};`
    return next()
  },
  function * (next) {
    this.body = `${this.body} prefix is ${this.route.prefix};`
    yield next
  },
  (ctx, next) => {
    ctx.body = `${ctx.body} and third middleware!`
    return next()
  }
)

// You can middlewares as array too
router.addRoute('GET', '/users/:user', [
  (ctx, next) => {
    ctx.body = `GET /users/${ctx.params.user}`
    console.log(ctx.route)
    return next()
  },
  function * (next) {
    this.body = `${this.body}, prefix is: ${this.route.prefix}`
    yield next
  }
])

// can use `koa@1` and `koa@2`, both works
let Koa = require('koa')
let app = new Koa()

app.use(router.middleware())
app.listen(4290, () => {
  console.log('Koa server start listening on port 4290')
})

.getRoute

Get a route by name. Name of each route is its pathname or route. For example: the name of .get('/cat/foo') route is /cat/foo, but if you pass cat/foo - it will work too.

Params

  • name {String}: name of the Route Object
  • returns {Object|Null}: Route Object, or null if not found

Example

let router = require('koa-better-router')().loadMethods()

router.get('/cat/foo', function (ctx, next) {})
router.get('/baz', function (ctx, next) {})

console.log(router.getRoute('baz'))      // => Route Object
console.log(router.getRoute('cat/foo'))  // => Route Object
console.log(router.getRoute('/cat/foo')) // => Route Object

.addRoutes

Concats any number of arguments (arrays of route objects) to the this.routes array. Think for it like registering routes. Can be used in combination with .createRoute and .getRoute.

Params

  • ...args {Array}: any number of arguments (arrays of route objects)
  • returns {KoaBetterRouter} this: instance for chaining

Example

let router = require('koa-better-router')()

// returns Route Object
let foo = router.createRoute('GET', '/foo', function (ctx, next) {
  ctx.body = 'foobar'
  return next()
})
console.log(foo)

let baz = router.createRoute('GET', '/baz/qux', function (ctx, next) {
  ctx.body = 'baz qux'
  return next()
})
console.log(baz)

// Empty array because we just
// created them, didn't include them
// as actual routes
console.log(router.routes.length) // 0

// register them as routes
router.addRoutes(foo, baz)

console.log(router.routes.length) // 2

.getRoutes

Simple method that just returns this.routes, which is array of route objects.

  • returns {Array}: array of route objects

Example

let router = require('koa-better-router')()

router.loadMethods()

console.log(router.routes.length) // 0
console.log(router.getRoutes().length) // 0

router.get('/foo', (ctx, next) => {})
router.get('/bar', (ctx, next) => {})

console.log(router.routes.length) // 2
console.log(router.getRoutes().length) // 2

.groupRoutes

Groups multiple "Route Objects" into one which middlewares will be these middlewares from the last "source". So let say you have dest route with 2 middlewares appended to it and the src1 route has 3 middlewares, the final (returned) route object will have these 3 middlewares from src1 not the middlewares from dest. Make sense? If not this not make sense for you, please open an issue here, so we can discuss and change it (then will change it in the koa-rest-router too, because there the things with method .groupResource are the same).

Params

  • dest {Object}: known as "Route Object"
  • src1 {Object}: second "Route Object"
  • src2 {Object}: third "Route Object"
  • returns {Object}: totally new "Route Object" using .createRoute under the hood

Example

let router = require('./index')({ prefix: '/api/v3' })

let foo = router.createRoute('GET /foo/qux/xyz', function (ctx, next) {})
let bar = router.createRoute('GET /bar', function (ctx, next) {})

let baz = router.groupRoutes(foo, bar)
console.log(baz)
// => Route Object {
//   prefix: '/api/v3',
//   path: '/api/v3/foo/qux/sas/bar',
//   pathname: '/foo/qux/sas/bar'
//   ...
// }

// Server part
let Koa = require('koa')
let app = new Koa()

router.addRoutes(baz)

app.use(router.middleware())
app.listen(2222, () => {
  console.log('Server listening on http://localhost:2222')

  router.getRoutes().forEach((route) => {
    console.log(`${route.method} http://localhost:2222${route.path}`)
  })
})

.extend

Extends current router with routes from router. This router should be an instance of KoaBetterRouter too. That is the correct extending/grouping of couple of routers.

Params

  • <router> {Object}: instance of KoaBetterRouter
  • returns {KoaBetterRouter} this

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap