本文首發於:用Decorator控制Koa路由javascript
在Spring中Controller長這樣html
@Controller public class HelloController{ @RequestMapping("/hello") String hello() { return "Hello World"; } }
還有Python上的Flask框架java
@app.route("/hello") def hello(): return "Hello World"
二者都用decorator來控制路由,這樣寫的好處是更簡潔、更優雅、更清晰。python
反觀Express或Koa上的路由瀏覽器
router.get('/hello', async ctx => { ctx.body = 'Hello World' })
徹底差了一個檔次babel
JS從ES6開始就有Decorator
了,只是瀏覽器和Node都尚未支持。須要用babel-plugin-transform-decorators-legacy
轉義。app
首先須要明確兩個概念:框架
Decorator基本原理:koa
@Controller class Hello{ } // 等同於 Controller(Hello)
Controller是個普通函數,target
爲修飾的類或方法async
// Decorator不傳參 function Controller(target) { } // Decorator傳參 function Controller(params) { return function (target) { } }
若是Decorator是傳參的,即便params有默認值,在調用時必須帶上括號,即:
@Controller() class Hello{ }
咱們能夠對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便可。