JS进步之路Node.js

Koa 路由自动化

2019-12-26  本文已影响0人  Qibing_Fang

因为工作和自身(偷懒)的原因,时隔5个多月没有写文章了,今日重新提笔

一、写作背景

二、思考过程 + 原理

三、项目实例

https://github.com/ShyGodB/qbfang-blog

// 定义一个过滤方法,通过请求路径获取文件路径和方法名
const filter = (ctx) => {
    // 此句代码是为了兼容get请求,如果只用 post 可忽略
    const url = ctx.url.split('?')[0].toLowerCase()
    // 通过js的split方法将请求路径打散,得到一个数组,方法名就是数组的最后一项
    const actions = url.split('/')
    // 根据自己的项目路径和请求路径拼接文件 url
    const methodUrl = '../src/control/' + actions[2] + '/' + actions[3]
    // 取得方法名字
    const methodName = actions[4]
    // 返回文件路径和方法名
    return { methodUrl, methodName }
}

// 暴露一个异步方法,供外部使用( app.js )
module.exports = async (ctx, next) => {
    // 执行过滤方法,获得文件路径和方法名
    const { methodUrl, methodName } = filter(ctx)
    // 通过 require 引入文件
    const obj = await require(methodUrl)
    // 获得并执行方法
    await obj[methodName](ctx);
    // 下一步
    await next()
};
const Koa = require('koa');
const json = require('koa-json');
// 引入文件 - route.js
const route = require('./api/route');
const bodyParser = require('koa-bodyparser');
const validate = require('koa-validate');
const mongodb = require('./config/mongodb');
const app = new Koa();
const port = 3000;

app.use(json());
// 通过 app.use 执行route.js 暴露出来的方法
app.use(route);
app.use(bodyParser());
validate(app);

(async () => {
    await mongodb.connect();
    app.listen(port, () => {
        console.log(`The servier is running at http:127.0.0.1:${port}`);
    });
})();

⚠️:

附:我的项目目录

==>


image.png

四、结束语

上一篇 下一篇

猜你喜欢

热点阅读