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

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

前言

在Spring中Controller长这样


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

还有Python上的Flask框架


@app.route("/hello")
def hello():
return "Hello World"

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

反观Express或Koa上的路由


router.get('/hello', async ctx => {
ctx.body = 'Hello World'
})

完全差了一个档次

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

Decorator基本原理

首先需要明确两个概念:

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

Decorator基本原理:


@Controller
class Hello{

}

// 等同于

Controller(Hello)

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


// Decorator不传参
function Controller(target) {

}

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

}
}

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


@Controller()
class Hello{

}

如何在Koa中使用Decorator

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

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


var Koa = require('koa');
var Router = require('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());

再想象一下最终目标


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

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


function Request({url, method}) {
return function (target, name, descriptor) {
let fn = descriptor.value
descriptor.value = (router) => {
router[method](url, async(ctx, next) => {
await fn(ctx, next)
})
}
}
}

对RequestMethod进行格式统一