or
Demoyarn add koa-dec-router
app.js
Â
import Koa from 'koa'
import DecRouter from 'koa-dec-router'
Â
const decRouter = DecRouter({
  controllersDir: `${__dirname}/controllers`,
  before: null,Â
  after: null,Â
})
Â
const app = new Koa()
Â
app.use(decRouter.router.routes())
app.use(decRouter.router.allowedMethods())
Â
controllers/api.js
import { controller, get, post } from 'dec-router'
Â
async function apiHandler(ctx, next) {
  console.log('handle all api and subclass\'s')
  await next()
}
Â
@controller('/api', apiHandler)
export default class Api {
  async getApiCommon(ctx) {
   Â
    returnÂ
  }
}
Â
controllers/posts.js
Console outputÂ
import { controller, get, post } from 'dec-router'
import Api from './api'
Â
async function postHandler(ctx, next) {
  console.log('handle post')
  await next()
}
Â
@controller('/subpost')
export class Subpost {
  @get('s')
  async list(ctx) {
    ctx.body = 'get subpost'
  }
Â
}
Â
@controller('/post')
export default class Post extends Api {
Â
  @get('s')Â
  async list(ctx) {
    const commonData = await super.getApiCommon()
    ctx.body = 'get posts'
  }
Â
  @get('/:id', {priority: -1})Â
  async get(ctx) {
    ctx.body = 'get' + ctx.params.id
  }
Â
  @get('/special')
  async special(ctx) {
    ctx.body = 'special post'
  }
}
Â
To output all routes generated by dec-router, you can run your app like
DEBUG=dec-router,your-app:* node ./your-app.js
For windows, using cross-env
API Reference DecRouter(options)cross-env DEBUG=dec-router,your-app:* node ./your-app.js
Controller decorator.
'/' + slug(cls.name)
, can be inheritedController method decorator, default would totally override superclass's method with same path (not same name), including method, opts, middlewares, etc.
'get', 'head', 'post', 'put', 'delete', 'patch', 'use'
;'/' + slug(method.name)
alias of @route('get', path, opts, ...middlewares)
@head(path, opts, ..middlewares)alias of @route('head', path, opts, ...middlewares)
@post(path, opts, ..middlewares)alias of @route('post', path, opts, ...middlewares)
@put(path, opts, ..middlewares)alias of @route('put', path, opts, ...middlewares)
@del(path, opts, ..middlewares)alias of @route('delete', path, opts, ...middlewares)
@patch(path, opts, ..middlewares)alias of @route('patch', path, opts, ...middlewares)
@all(path, opts, ..middlewares)alias of @route('use', path, opts, ...middlewares)
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