工程化批处理

本文最后更新于:2022年4月21日 上午

1. 批量注册中间件

./controllers中

controllerA.js
controllerB.js
controllerC.js
./controllers/index.js

const _ = require('lodash')
const fs = require('fs')
const path = require('path')

/**
 * 映射文件夹下的文件为模块
 */
const mapDir = d => {
    const tree = {}

    // 获得当前文件夹下的所有的文件夹和文件
    const [dirs, files] = _(fs.readdirSync(d))
        .partition(p => fs.statSync(path.join(d, p)).isDirectory())
    // _(value)
    // 创建一个经 lodash 包装后的对象会启用隐式链。返回的数组、集合、方法相互之间能够链式调用

    // 递归映射文件夹
    dirs.forEach(dir => {
        tree[dir] = mapDir(path.join(d, dir))
    })

    // 映射文件
    files.forEach(file => {
        if (path.extname(file) === '.js') {
            tree[path.basename(file, '.js')] = require(path.join(d, file))
        }
    })

    return tree
}

// 默认导出当前文件夹下的映射
module.exports = mapDir(path.join(__dirname))
  • 使用
const controllers = require("../controllers");

router.get("/A", controllers.controllerA);
router.post("/B", controllers.controllerB);
router.post("/C", controllers.controllerC);

2. 批量注册路由

  • /routes/...
/a.js
{
    const router = require('koa-router')()

    router.get('/xxx',()=>{
        ctx.....
    })

    return router
}
...
b.js
c.js
d.js
  • /router/index.js
const router = require("koa-router")();
const fs = require("fs");
const path = require("path");

const mapRoutes = (filePath) => {
	const files = fs.readdirSync(filePath); //将当前目录下 都读出来

	files
		.filter((file) => {
			// 过滤

			if (filePath !== __dirname && file === "index.js") {
				//读取的时候会将当前目录的 index.js 也读取出来,这个不需要,如果拿到别的地方可以不加这个判断

				console.log("routes module must not be 'index.js' ");
			}

			return file !== "index.js";
		}) // 将 index.js 过滤掉,路由名字一律不能用 index.js 命名,否则不生效,我这里边的 index.js 如果拿到外面就不用添加这个判断了 ...
		.forEach((file) => {
			let newFilePath = path.join(filePath, file);

			if (fs.statSync(newFilePath).isDirectory()) {
				// 是目录

				loadRoutes(newFilePath); // 递归
			} else {
				// 是文件

				let route = require(newFilePath);

				//注册路由
				router.use(route.routes());
				router.use(route.allowedMethods());
			}
		});
};

mapRoutes(path.join(__dirname));

module.exports = router;
  • app.js
const routes = require("./routes/index");
app.use(routes.routes(), routes.allowedMethods());

工程化批处理
http://yoursite.com/2022/02/24/批量映射模块/
作者
tatekii
发布于
2022年2月24日
许可协议