微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

前言

在Spring中Controller长这样

rush:java;"> @Controller public class HelloController{ @RequestMapping("/hello") String hello() { return "Hello World"; } }

还有Python上的Flask框架

rush:py;"> @app.route("/hello") def hello(): return "Hello World"

两者都用decorator来控制路由,这样写的好处是更简洁、更优雅、更清晰。

反观Express或Koa上的路由

{ ctx.body = 'Hello World' })

完全差了一个档次

JS从ES6开始就有Decorator了,只是浏览器和Node都还没有支持。需要用babel-plugin-transform-decorators-legacy转义。

Decorator基本原理

首先需要明确两个概念:

  • Decorator只能作用于类或类的方法
  • 如果一个类和类的方法都是用了Decorator,类方法的Decorator优先于类的Decorator执行

Decorator基本原理:

rush:js;"> @Controller class Hello{

}

// 等同于

Controller(Hello)

Controller是个普通函数,target为修饰的类或方法

rush:js;"> // Decorator不传参 function Controller(target) {

}

// Decorator传参
function Controller(params) {
return function (target) {

}
}

如果Decorator是传参的,即使params有认值,在调用时必须带上括号,即:

rush:js;"> @Controller() class Hello{

}

如何在Koa中使用Decorator

我们可以对koa-router中间件进行包装

先回顾一下koa-router基本使用方法

var app = new Koa();
var router = new Router();

router.get('/',async (ctx,next) => {
// ctx.router available
});

app
.use(router.routes())
.use(router.allowedMethods());

再想象一下最终目标

rush:js;"> @Controller({prefix: '/hello'}) class HelloController{ @Request({url: '/',method: RequestMethod.GET}) async hello(ctx) { ctx.body = 'Hello World' } }

类内部方法的装饰器是优先执行的,我们需要对方法重新定义

{ router[method](url,async(ctx,next) => { await fn(ctx,next) }) } } }

对RequestMethod进行格式统一

rush:js;"> const RequestMethod = { GET: 'get',POST: 'post',PUT: 'put',DELETE: 'delete' }

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

rush:js;"> 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
}
}

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

rush:js;"> 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即可。

总结

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐