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

tunnckoCore/koa-rest-router: Most powerful, flexible and composable router for b ...

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

开源软件名称:

tunnckoCore/koa-rest-router

开源软件地址:

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

开源编程语言:

JavaScript 100.0%

开源软件介绍:

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

Most powerful, flexible and composable router for building enterprise RESTful APIs easily!

codeclimate codestyle linux build windows build codecov dependency status

You might also be interested in gibon - a minimal & functional 600 bytes client-side router.

Highlighs

  • production: ready for and used in
  • composability: grouping multiple resources and multiple routers
  • flexibility: overriding controller and request methods, plus custom prefixes
  • 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
  • backward compatible: works on koa v1 - use .legacyMiddleware
  • maintainability: very small, beautiful, maintainable and commented codebase
  • stability: strict semantic versioning and very well documented, based on koa-better-router
  • open: love PRs for features, issues and recipes - Contribute a recipe? See the recipes of koa-better-router

Table of Contents

(TOC generated by verb using markdown-toc)

ProTip: Checkout koa-better-router API too to know what more methods comes with this.

Quickstart

This router uses koa-better-router, so you should review its API documentation to get more info how the things are working and what more methods are exposed.

Controller methods mapping

In addition this router allows you to override the controller methods which will be used in certain route path.

Defaults

Request method Route path Controller method
GET /users index
GET /users/new new
POST /users create
GET /users/:user show
GET /users/:user/edit edit
PUT /users/:user update
DELETE /users/:user remove

Example

let Router = require('koa-rest-router')
let router = Router()

router.resource('users', {
  // GET /users
  index: (ctx, next) => {},

  // GET /users/new
  new: (ctx, next) => {},

  // POST /users
  create: (ctx, next) => {},

  // GET /users/:user
  show: (ctx, next) => {},

  // GET /users/:user/edit
  edit: (ctx, next) => {},

  // PUT /users/:user
  update: (ctx, next) => {},

  // DELETE /users/:user
  remove: (ctx, next) => {}
})

let users = router.getResource('users')

console.log(users.length) // => 7
console.log(users) // => Array Route Objects

console.log(router.routes.length) // => 7
console.log(router.resources.length) // => 1

Note: Multiple middlewares can be passed on each. Also combining old and modern koa middlewares, so both generator functions and normal functions.

Overriding controller methods

You easily can override the defaults by passing options.map object with key/value pairs where the key represents the original, and value is a string containing the wanted override.

Example

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

let options = {
  map: {
    index: 'foo',
    new: 'bar',
    create: 'baz',
    show: 'qux',
  }
}

router.resource('users', {
  // GET /users
  foo: (ctx, next) => {},

  // GET /users/new
  bar: (ctx, next) => {},

  // POST /users
  baz: (ctx, next) => {},

  // GET /users/:user
  qux: (ctx, next) => {},

  // ... etc
}, options)

Overriding request methods

In some cases in guides the REST routes uses different request methods and that field is not clear enough. So every sane router should allow overriding such things, so we do it. By default for updating is used PUT, for deleting/removing is DELETE. You can override this methods to use POST instead, so ...

Example

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

let options = {
  methods: {
    put: 'POST'
  }  
}

router.resource('cats', {
  // POST /cats/:cat
  update: (ctx, next) => {}
}, options)

And you can combine both overriding variants, of course

Example

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

let options = {
  methods: {
    put: 'POST'
  },
  map: {
    update: 'foobar'
  }
}

router.resource('cats', {
  // POST /cats/:cat
  foobar: (ctx, next) => {}
}, options)

Install

Install with npm

$ npm i koa-rest-router --save

Usage

For more use-cases see the tests

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

// or

let Router = require('koa-rest-router')
let apiRouter = Router({ prefix: '/api/v1' })

API

KoaRestRouter

Initialize KoaRestRouter with optional options, directly passed to koa-better-router and this package inherits it. So you have all methods and functionality from the awesome koa-better-router middleware.

Params

  • [options] {Object}: passed directly to koa-better-router, in addition we have 2 more options here.
  • [options.methods] {Object}: override request methods to be used
  • [options.map] {Object}: override controller methods to be called

Example

let Router = require('koa-rest-router')
let api = Router({ prefix: '/api/v1' })

// - can have multiples middlewares
// - can have both old and modern middlewares combined
api.resource('companies', {
  index: function (ctx, next) {},
  show: function (ctx, next) {},
  create: function (ctx, next) {}
  // ... and etc
})

console.log(api.routes.length) // 7
console.log(api.resources.length) // 1

api.resource('profiles', {
  index: function (ctx, next) {},
  show: function (ctx, next) {},
  create: function (ctx, next) {}
  // ... and etc
})

console.log(api.routes.length) // 14
console.log(api.resources.length) // 2

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

let basic = Router() // prefix is `/` by default
basic.extend(api)

app.use(api.middleware())
app.use(basic.middleware())

app.listen(4444, () => {
  console.log('Open http://localhost:4444 and try')
  // will output 2x14 links
  // - 14 links on `/api/v1` prefix
  // - 14 links on `/` prefix
  api.routes.forEach((route) => {
    console.log(`${route.method} http://localhost:4444${route.path}`)
  })
  basic.routes.forEach((route) => {
    console.log(`${route.method} http://localhost:4444${route.path}`)
  })
})

.createResource

Core method behind .resource for creating single resource with a name, but without adding it to this.routes array. You can override any defaults - default request methods and default controller methods, just by passing respectively opts.methods object and opts.map object. It uses koa-better-router's .createRoute under the hood.

Params

  • name {String|Object}: name of the resource or ctrl
  • ctrl {Object}: controller object to be called on each endpoint, or opts
  • opts {Object}: optional, merged with options from constructor
  • returns {KoaRestRouter} this: instance for chaining

Example

let router = require('koa-rest-router')({
  prefix: '/api'
}).loadMethods()

// The server part
let body = require('koa-better-body')
let Koa = require('koa')
let app = new Koa()

// override request methods
let methods = {
  put: 'POST'
  del: 'POST'
}

// override controller methods
let map = {
  index: 'list',
  show: 'read',
  remove: 'destroy'
}

// notice the body should be invoked explicitly
// with or without options object, no matter
let updateMiddlewares = [body(), (ctx, next) => {
  ctx.body = `This method by default is triggered with PUT requests only.`
  ctx.body = `${ctx.body} But now it is from POST request.`
  return next()
}, function * (next) => {
  this.body = `${this.body} Incoming data is`
  this.body = `${this.body} ${JSON.stringify(this.request.fields, null, 2)}`
  yield next
}]

// create actual resource
let cats = router.createResource('cats', {
  list: [
    (ctx, next) => {
      ctx.body = `This is GET ${ctx.route.path} route with multiple middlewares`
      return next()
    },
    function * (next) {
      this.body = `${this.body} and combining old and modern middlewares.`
      yield next
    }
  ],
  read: (ctx, next) => {
    ctx.body = `This is ${ctx.route.path} route.`
    ctx.body = `${ctx.body} And param ":cat" is ${ctx.params.cat}.`
    ctx.body = `${ctx.body} By default this method is called "show".`
    return next()
  },
  update: updateMiddlewares,
  destroy: (ctx, next) => {
    ctx.body = `This route should be called with DELETE request, by default.`
    ctx.body = `${ctx.body} But now it request is POST.`
    return next()
  }
}, {map: map, methods: methods})

console.log(cats)
// => array of "Route Objects"

// router.routes array is empty
console.log(router.getRoutes()) // => []

// register the resource
router.addResource(cats)

console.log(router.routes.length) // => 7
console.log(router.getRoutes().length) // => 7
console.log(router.getRoutes()) // or router.routes
// => array of "Route Objects"

app.use(router.middleware())

app.listen(5000, () => {
  console.log(`Server listening on http://localhost:5000`)
  console.log(`Try to open these routes:`)

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

.addResource

Simple method that is alias of .addRoutes and .addResources, but for adding single resource. It can accepts only one resource object.

Params

  • resource {Array}: array of route objects, known as "Resource Object"
  • returns {KoaRestRouter} this: instance for chaining

Example

let Router = require('koa-rest-router')
let api = new Router({
  prefix: '/'
})

console.log(api.resources.length) // 0
console.log(api.routes.length) // 0

api.addResource(api.createResource('dragons'))

console.log(api.resources.length) // 1
console.log(api.routes.length) // 7

console.log(api.getResource('dragons'))
// array of route objects
// => [
//   { prefix: '/', route: '/dragons', path: '/dragons', ... }
//   { prefix: '/', route: '/dragons/:dragon', path: '/dragons/:dragon', ... }
 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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