Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > javascript技巧

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

来源:中文源码网    浏览:289 次    日期:2024-04-27 15:09:52
【下载文档:  利用Decorator如何控制Koa路由详解.txt 】


利用Decorator如何控制Koa路由详解
前言
在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进行格式统一
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即可。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对中文源码网的支持。

相关内容