A RetroSearch Logo

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

Search Query:

Showing content from https://github.com/gyson/koa-simple-router below:

gyson/koa-simple-router: Simple router for koa 2.x

Simple and fast router for koa 2.x

$ npm install koa-simple-router
const Koa = require('koa') // koa 2.x
const router = require('koa-simple-router')

let app = new Koa()

app.use(router(_ => {
  _.get('/', (ctx, next) => {
    ctx.body = 'hello'
  })
  _.post('/name/:id', (ctx, next) => {
    // ...
  })
})

Create a router middleware with init function.

const Koa = require('koa')
const router = require('koa-simple-router')
const app = new Koa()

app.use(router(_ => {
  _.get('/', (ctx, next) => {

  })
  _.post('/path', (ctx, next) => {

  })
}))

Create a router middleware with options and init function.

Default options is the same as path-to-regexp.

const Koa = require('koa')
const router = require('koa-simple-router')
const app = new Koa()

app.use(router({ prefix: '/api' }, _ => {
  _.get('/:user/id', (ctx, next) => {

  })
  _.post('/:user/id', (ctx, next) => {

  })
}))
app.use(router(_ => {
  _.get('/path',
    (ctx, next) => {},
    (ctx, next) => {},
    (ctx, next) => {}
  )
}))
_.all(path, ...[mw | obj])

Middleware mode: works just like _.verb(path, ...mw) but ignore ctx.method

app.use(router(_ => {
  _.all('/path/to/:recource', (ctx, next) => {

  })
}))

Object mode: accept an object with method as key and middleware or array of middleware as value

app.use(router(_ => {
  _.all('/path/to/:recource', {
    get: (ctx, next) => {
      // ...
    },
    post: (ctx, next) => {
      // ...
    },
    put: (ctx, next) => {
      // ...
    },
    delete: (ctx, next) => {
      // ...
    }
    // Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS
  })
}))

which is equivalent to

app.use(router(_ => {
  _.all('/path/to/:recource', (ctx, next) => {
    switch (ctx.method) {
      case 'GET':
      case 'HEAD':
        // ...
        break
      case 'POST':
        // ...
        break
      case 'PUT':
        // ...
        break
      case 'DELETE':
        // ...
        break
      case 'OPTIONS':
        ctx.status = 200
        ctx.set('Allow', 'GET, HEAD, POST, PUT, DELETE, OPTIONS')
        break
      default:
        ctx.status = 405 // method not allowed
        ctx.set('Allow', 'GET, HEAD, POST, PUT, DELETE, OPTIONS')
    }
  }
}))

Register middleware for named route parameters.

app.use(router(_ => {
  _.param('user', async (ctx, next) => {
    ctx.user = await User.find(ctx.params.user)
    // ...
    return next()
  })

  _.get('/:user/do-x', (ctx, next) => {

  })

  _.post('/:user/do-y', (ctx, next) => {

  })
}))

MIT


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