Files
bamboo/middleware/router/index.js
T
2022-06-04 11:43:05 +08:00

51 lines
1.3 KiB
JavaScript

'use strict';
/**
* 加载api路由
* 加载app/api目录下的文件到路由
*/
const Router = require('koa-router')
const config = require("./config")
// 错误处理
module.exports = {
sort : 999, //排序
use : true, // 是否使用
loadFun: async (app, fun) => { // 自行定义中间件的加载方式,将覆盖默认加载方法
const router = await fun(app)
app.use(router.routes()).use(router.allowedMethods())
},
fun : async (app) => {
const router = new Router({ //设置前缀
prefix: config.prefix
});
let list = await app.load(config.path)
list.forEach(item => {
const url = item.res.path ? item.res.path : '/' + item.parse.father + '/api/' + item.parse.name
router.all(url, async (ctx, next) => {
/*处理body结果*/
try {
const res = await item.res.fun(ctx, app)
if (!ctx.body) {
if (res) {
ctx.body = app.res.success(res)
} else if (res === false) {
ctx.body = app.res.error()
} else {
ctx.body = app.res.success()
}
}
} catch (err) {
console.log(err);
ctx.body = app.res.error(null, "系统错误", 500)
ctx.status = 500
}
//是否跟随body结果
ctx.status = config.statusTobody ? ctx.body.status || 400 : 200
await next();
})
})
return router
}
}