使用es6装饰器(Decorator) 优化 koa2 路由

日期: 2019-06-18         浏览量: 6261

此处不对es6 Decorator 方法做讲解,请自行谷歌或百度。(因为讲解不明白哈哈)


看看要实现的样子:



@Controller('/v1/account')
class Account{
    
    @Action('/getAccountList', GET, isAuth)
    async getAccountList(ctx){
        console.log(ctx);
    }

    @Action('/delAccount', GET, isAuth)
    delAccount(ctx){
        console.log(ctx);
    }
}


开始实现(实现说明:基于koa框架,使用koa-router)


1. 安装依赖包(Decorator 只是一个提案, node 并未支持,需要安装bable)



npm i babel-plugin-transform-decorators-legacy --save
npm i babel-register --save



2. 配置bable (在项目根目录创建.babelrc文件,写入如下内容)


{
    "plugins": ["transform-decorators-legacy"]
}


3. 在app.js 启动文件使用bable


const koa = require('koa');
const app = new koa();
require("babel-register");    //添加这一行



4. 创建 core 目录 并创建 router.js 文件 (写入如下内容


const router = require('koa-router')();

module.exports = {

    Controller: (name) => {
        return function (target) {
            let reqList = Object.getOwnPropertyDescriptors(target.prototype)
            for (let v in reqList) {
                // 排除类的构造方法
                if (v !== 'constructor') {
                    let fn = reqList[v].value
                    fn(name)
                }
            }
            return router
        }
        
    },

    Action:(path, method, auth = false)=>{
        return (target, property, descriptor)=>{
            let fn = descriptor.value
            descriptor.value = (name) => {
                if(auth){
                    router[method](`${name}${path}`, auth, fn);
                }else{
                    router[method](`${name}${path}`, fn);
                }       
            }
        }
    },

    POST: 'post',
    GET: 'get',
    DELETE: 'delete',
    PUT: 'put',
    ALL: 'all'
}


5. 在 controllers 目录,业务逻辑文件中我们就可以这样写了



const { Controller, Action, POST, GET } = require('../../lib/core/router');

@Controller('/v1/account')
class Account{
    
    @Action('/getAccountList', GET)
    async getAccountList(ctx){
        return ctx.body = 'hellow word';
    }

    @Action('/delAccount', GET)
    delAccount(ctx){
        return ctx.body = 'hellow word';
    }
}
module.exports = Account;
 


6. 在core目录下创建routerinit.js文件(写入如下内容)



const glob = require('glob');   //需安装glob包
module.exports = (app) =>{
    //__ROOTPATH__   自定义全局根路径变量 注意路径
    glob.sync(__ROOTPATH__ + '/controllers/**/*.js').forEach(file => {
        let router = require(file);
        app.use(router.routes(), router.allowedMethods());
    });
}



7. 在app.js中使用routerinit.js文件



const routers = require('./core/routerinit.js');
routers(app);



完美结束,启动你的项目看看吧。