利用Decorator怎樣控制Koa路由

小編給大家分享一下利用Decorator怎樣控制Koa路由,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

創(chuàng)新互聯(lián)公司公司2013年成立,先為華容等服務(wù)建站,華容等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為華容企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

前言

在Spring中Controller長這樣

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

還有Python上的Flask框架

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

兩者都用decorator來控制路由,這樣寫的好處是更簡(jiǎn)潔、更優(yōu)雅、更清晰。

反觀Express或Koa上的路由

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

完全差了一個(gè)檔次

JS從ES6開始就有Decorator了,只是瀏覽器和Node都還沒有支持。需要用babel-plugin-transform-decorators-legacy轉(zhuǎn)義。

Decorator基本原理

首先需要明確兩個(gè)概念:

  • Decorator只能作用于類或類的方法上

  • 如果一個(gè)類和類的方法都是用了Decorator,類方法的Decorator優(yōu)先于類的Decorator執(zhí)行

Decorator基本原理:

@Controller
class Hello{

}

// 等同于

Controller(Hello)

Controller是個(gè)普通函數(shù),target為修飾的類或方法

// Decorator不傳參
function Controller(target) {

}

// Decorator傳參
function Controller(params) {
 return function (target) {

 }
}

如果Decorator是傳參的,即使params有默認(rèn)值,在調(diào)用時(shí)必須帶上括號(hào),即:

@Controller()
class Hello{

}

如何在Koa中使用Decorator

我們可以對(duì)koa-router中間件進(jìn)行包裝

先回顧一下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());

再想象一下最終目標(biāo)

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

類內(nèi)部方法的裝飾器是優(yōu)先執(zhí)行的,我們需要對(duì)方法重新定義

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)
  })
 }
 }
}

對(duì)RequestMethod進(jìn)行格式統(tǒng)一

const RequestMethod = {
 GET: 'get',
 POST: 'post',
 PUT: 'put',
 DELETE: 'delete'
}

Controller裝飾器需將Request方法添加到Router實(shí)例并返回Router實(shí)例

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) {
  // 排除類的構(gòu)造方法
  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實(shí)例中同路由一樣use即可。

以上是“利用Decorator怎樣控制Koa路由”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

網(wǎng)頁標(biāo)題:利用Decorator怎樣控制Koa路由
本文鏈接:http://bm7419.com/article42/gijohc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、動(dòng)態(tài)網(wǎng)站網(wǎng)站建設(shè)、外貿(mào)建站、定制網(wǎng)站標(biāo)簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營