利用Decorator如何控制Koa路由详解

2020-06-17 06:43:07易采站长站整理

const RequestMethod = {
GET: 'get',
POST: 'post',
PUT: 'put',
DELETE: 'delete'
}

Controller装饰器需将Request方法添加到Router实例并返回Router实例


import KoaRouter from 'koa-router'

function Controller({prefix}) {
let router = new KoaRouter()
if (prefix) {
router.prefix(prefix)
}
return function (target) {
let reqList = Object.getOwnPropertyDescriptors(target.prototype)
for (let v in reqList) {
// 排除类的构造方法
if (v !== 'constructor') {
let fn = reqList[v].value
fn(router)
}
}
return router
}
}

至此,装饰器基本功能就完成了,基本使用方法为:


import {Controller, Request, RequestMethod} from './decorator'

@Controller({prefix: '/hello'})
export default class HelloController{
@Request({url: '/', method: RequestMethod.GET})
async hello(ctx) {
ctx.body = 'Hello World'
}
}

在App实例中同路由一样use即可。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对软件开发网的支持。