利用Decorator如何控制Koa路由详解
前言
在Spring中Controller长这样
@Controller
publicclassHelloController{
@RequestMapping("/hello")
Stringhello(){
return"HelloWorld";
}
}
还有Python上的Flask框架
@app.route("/hello")
defhello():
return"HelloWorld"
两者都用decorator来控制路由,这样写的好处是更简洁、更优雅、更清晰。
反观Express或Koa上的路由
router.get('/hello',asyncctx=>{
ctx.body='HelloWorld'
})
完全差了一个档次
JS从ES6开始就有Decorator了,只是浏览器和Node都还没有支持。需要用babel-plugin-transform-decorators-legacy转义。
Decorator基本原理
首先需要明确两个概念:
- Decorator只能作用于类或类的方法上
- 如果一个类和类的方法都是用了Decorator,类方法的Decorator优先于类的Decorator执行
Decorator基本原理:
@Controller
classHello{
}
//等同于
Controller(Hello)
Controller是个普通函数,target为修饰的类或方法
//Decorator不传参
functionController(target){
}
//Decorator传参
functionController(params){
returnfunction(target){
}
}
如果Decorator是传参的,即使params有默认值,在调用时必须带上括号,即:
@Controller()
classHello{
}
如何在Koa中使用Decorator
我们可以对koa-router中间件进行包装
先回顾一下koa-router基本使用方法:
varKoa=require('koa');
varRouter=require('koa-router');
varapp=newKoa();
varrouter=newRouter();
router.get('/',async(ctx,next)=>{
//ctx.routeravailable
});
app
.use(router.routes())
.use(router.allowedMethods());
再想象一下最终目标
@Controller({prefix:'/hello'})
classHelloController{
@Request({url:'/',method:RequestMethod.GET})
asynchello(ctx){
ctx.body='HelloWorld'
}
}
类内部方法的装饰器是优先执行的,我们需要对方法重新定义
functionRequest({url,method}){
returnfunction(target,name,descriptor){
letfn=descriptor.value
descriptor.value=(router)=>{
router[method](url,async(ctx,next)=>{
awaitfn(ctx,next)
})
}
}
}
对RequestMethod进行格式统一
constRequestMethod={
GET:'get',
POST:'post',
PUT:'put',
DELETE:'delete'
}
Controller装饰器需将Request方法添加到Router实例并返回Router实例
importKoaRouterfrom'koa-router'
functionController({prefix}){
letrouter=newKoaRouter()
if(prefix){
router.prefix(prefix)
}
returnfunction(target){
letreqList=Object.getOwnPropertyDescriptors(target.prototype)
for(letvinreqList){
//排除类的构造方法
if(v!=='constructor'){
letfn=reqList[v].value
fn(router)
}
}
returnrouter
}
}
至此,装饰器基本功能就完成了,基本使用方法为:
import{Controller,Request,RequestMethod}from'./decorator'
@Controller({prefix:'/hello'})
exportdefaultclassHelloController{
@Request({url:'/',method:RequestMethod.GET})
asynchello(ctx){
ctx.body='HelloWorld'
}
}
在App实例中同路由一样use即可。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。