分享一个基于 decorators 和 es6 类继承的 koa 路由
decorators 和 ES6 class 的完美结合,支持class路径继承,class中间件继承,自动加载控制器,路由优先级,灵活的配置策略,满足各种复杂业务逻辑。
app.js
import Koa from 'koa'
import DecRouter from 'koa-dec-router'
const decRouter = DecRouter({
controllersDir: `${__dirname}/controllers`,
before: null, // global middleware
after: null, // global middleware
})
const app = new Koa()
// decRouter.router: `koa-router` instance
app.use(decRouter.router.routes())
app.use(decRouter.router.allowedMethods())
controllers/api.js
import { controller, get, post } from 'koa-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 // some common data
}
}
controllers/posts.js
import { controller, get, post } from 'koa-dec-router'
import Api from './api'
async function postHandler(ctx, next) {
console.log('handle post')
await next()
}
// define multi controller class in one file. You can passing {expose: false} to disable exposing this controller, which can still be inherit.
@controller('/subpost')
export class Subpost {
@get('s')
async list(ctx) {
ctx.body = 'get subpost'
}
}
@controller('/post')
export default class Post extends Api {
@get('s') // final path = parent controller path + controller path + method path
async list(ctx) {
const commonData = await super.getApiCommon()
ctx.body = 'get posts'
}
@get('/:id', {priority: -1}) // wildcard using low priority, let `special` method handle first
async get(ctx) {
ctx.body = 'get' + ctx.params.id
}
@get('/special')
async special(ctx) {
ctx.body = 'special post'
}
}
欢迎 fork & star https://github.com/zaaack/koa-dec-router
来自酷炫的 CNodeMD