A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.npmjs.com/package/koa-rest-router below:

koa-rest-router - npm

koa-rest-router

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

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

Highlighs 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', {

  

  index: (ctx, next) => {},

 

  

  new: (ctx, next) => {},

 

  

  create: (ctx, next) => {},

 

  

  show: (ctx, next) => {},

 

  

  edit: (ctx, next) => {},

 

  

  update: (ctx, next) => {},

 

  

  remove: (ctx, next) => {}

})

 

let users = router.getResource('users')

 

console.log(users.length) 

console.log(users) 

 

console.log(router.routes.length) 

console.log(router.resources.length) 

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', {

  

  foo: (ctx, next) => {},

 

  

  bar: (ctx, next) => {},

 

  

  baz: (ctx, next) => {},

 

  

  qux: (ctx, next) => {},

 

  

}, 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', {

  

  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', {

  

  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')()

 

 

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

Example

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

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

 

api.resource('companies', {

  index: function (ctx, next) {},

  show: function (ctx, next) {},

  create: function (ctx, next) {}

  

})

 

console.log(api.routes.length) 

console.log(api.resources.length) 

 

api.resource('profiles', {

  index: function (ctx, next) {},

  show: function (ctx, next) {},

  create: function (ctx, next) {}

  

})

 

console.log(api.routes.length) 

console.log(api.resources.length) 

 

let Koa = require('koa') 

let app = new Koa()

 

let basic = Router() 

basic.extend(api)

 

app.use(api.middleware())

app.use(basic.middleware())

 

app.listen(4444, () => {

  console.log('Open http://localhost:4444 and try')

  

  

  

  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

Example

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

  prefix: '/api'

}).loadMethods()

 

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

let Koa = require('koa')

let app = new Koa()

 

let methods = {

  put: 'POST'

  del: 'POST'

}

 

let map = {

  index: 'list',

  show: 'read',

  remove: 'destroy'

}

 

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

}]

 

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)

 

console.log(router.getRoutes()) 

 

router.addResource(cats)

 

console.log(router.routes.length) 

console.log(router.getRoutes().length) 

console.log(router.getRoutes()) 

 

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:

  }))

})

.addResource

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

Params

Example

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

let api = new Router({

  prefix: '/'

})

 

console.log(api.resources.length) 

console.log(api.routes.length) 

 

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

 

console.log(api.resources.length) 

console.log(api.routes.length) 

 

console.log(api.getResource('dragons'))

.getResource

Get single resource by name. Special case is resource to the / prefix. So pass / as name. See more on what are the "Route Objects" in the koa-better-router docs. What that method returns, I call "Resource Object" - array of "Route Objects"

Params

Example

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

  prefix: '/api/v2'

})

 

let frogs = api.createResource('frogs')

let dragons = api.createResource('dragons')

 

console.log(api.getResource('frogs'))

 

console.log(api.getResources().length) 

.resource

Creates a resource using .createResource and adds the resource routes to the this.routes array, using .addResource. This is not an alias! It is combination of two methods. Methods that are not defined in given ctrl (controller) returns by default 501 Not Implemented. You can override any defaults - default request methods and default controller methods, just by passing respectively opts.methods object and opts.map object.

Params

Example

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

 

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

let router = new Router() 

 

 

api.resource('users', {

  

  index: [(ctx, next) => {}, (ctx, next) => {}],

 

  

  new: (ctx, next) => {},

 

  

  create: (ctx, next) => {},

 

  

  show: [(ctx, next) => {}, function * (next) {}],

 

  

  edit: (ctx, next) => {},

 

  

  

  update: (ctx, next) => {},

 

  

  

  remove: (ctx, next) => {}

})

 

router.resource({

  

  foo: [

    (ctx, next) => {

      ctx.body = `GET ${ctx.route.path}`

      return next()

    },

    function * (next) {

      ctx.body = `${this.body}! Hello world!`

      yield next

    }

  ],

  

  show: (ctx, next) => {

    ctx.body = JSON.stringify(ctx.params, null, 2)

    return next()

  }

}, {

  map: {

    index: 'foo'

  }

})

 

api.routes.forEach(route => console.log(route.method, route.path))

router.routes.forEach(route => console.log(route.method, route.path))

 

let fooRouter = new Router()

let Koa = require('koa')

let app = new Koa()

 

fooRouter.addRoutes(api.getResources(), router.getRoutes())

 

console.log(fooRouter.routes)

console.log(fooRouter.routes.length) 

 

app.use(fooRouter.middleware())

 

app.listen(4433, () => {

  console.log('Cool server started at 4433. Try these routes:')

 

  fooRouter.routes.forEach((route) => {

    console.log(`${route.method} http://localhost:4433${route.path}`)

  })

})

.addResources

Just an alias of koa-better-router's' .addRoutes method.

Params

.getResources

As we have .getRoutes method for getting this.routes, so we have .getResources for getting this.resources array, too. Each .createResource returns array of route objects with length of 7, so 7 routes. So if you call .createResource two times the this.resources (what this method returns) will contain 2 arrays with 7 routes in each of them.

Example

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

 

console.log(router.routes.length)          

console.log(router.getRoutes().length)     

 

console.log(router.resources.length)       

console.log(router.getResources().length)  

 

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

router.resource('dogs')

router.resource('cats')

 

console.log(router.routes.length)          

console.log(router.getRoutes().length)     

 

console.log(router.resources.length)       

console.log(router.getResources().length)  

.groupResources

Powerful method for grouping couple of resources into one resource endpoint. For example you have /cats and /dogs endpoints, but you wanna create /cats/:cat/dogs/:dog endpoint, so you can do such things with that. You can group infinite number of resources. Useful methods that gives you what you should pass as arguments here are .createResource, .createRoute, .getResources, .getResource and .getRoutes. Note: Be aware of that it replaces middlewares of dest with the middlewares of last src.

Params

Example

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

 

let departments = router.createResource('departments')

let companies = router.createResource('companies')

let profiles = router.createResource('profiles')

let clients = router.createResource('clients')

let users = router.createResource('users')

let cats = router.createResource('cats')

let dogs = router.createResource('dogs')

 

let one = router.groupResources(companies, departments)

 

let two = router.groupResources(profiles, clients, cats)

 

let foo = router.groupResources(one, two)

 

router.addRoutes(one, foo)

 

let Koa = require('koa')

let app = new Koa()

 

app.use(router.middleware())

 

app.listen(4000, () => {

  console.log(`Mega API server on http://localhost:4000`)

  console.log(`Checkout these routes:`)

 

  

  router.getRoutes().forEach((route) => {

    console.log(`${route.method} http://localhost:4000${route.path}`)

  })

})

Related Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Please read the contributing guidelines for advice on opening issues, pull requests, and coding standards.
If you need some help and can spent some cash, feel free to contact me at CodeMentor.io too.

In short: If you want to contribute to that project, please follow these things

  1. Please DO NOT edit README.md, CHANGELOG.md and .verb.md files. See "Building docs" section.
  2. Ensure anything is okey by installing the dependencies and run the tests. See "Running tests" section.
  3. Always use npm run commit to commit changes instead of git commit, because it is interactive and user-friendly. It uses commitizen behind the scenes, which follows Conventional Changelog idealogy.
  4. Do NOT bump the version in package.json. For that we use npm run release, which is standard-version and follows Conventional Changelog idealogy.

Thanks a lot! :)

Contributing Recipes

Recipes are just different use cases, written in form of README in human language. Showing some "Pro Tips" and tricks, answering common questions and so on. They look like tests, but in more readable and understandable way for humans - mostly for beginners that not reads or understand enough the README or API and tests.

It would be great if you follow these steps when you want to fix, update or create a recipes. 😎

It will help a lot, thanks in advance! 😋

Building docs

Documentation and that readme is generated using verb-generate-readme, which is a verb generator, so you need to install both of them and then run verb command like that

$ npm install verbose/verb#dev verb-generate-readme --global && verb

Please don't edit the README directly. Any changes to the readme must be made in .verb.md.

Running tests

Clone repository and run the following in that cloned directory

$ npm install && npm test
Author

Charlike Mike Reagent

License

Copyright © 2016-2017, Charlike Mike Reagent. Released under the MIT license.

This file was generated by verb-generate-readme, v0.4.1, on February 14, 2017.
Project scaffolded using charlike cli.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4