优化架构,新增路由
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
/*封装入参*/
|
||||
module.exports = {
|
||||
sort: 3, //排序
|
||||
use : true, // 是否使用
|
||||
fun : async (ctx, next, app) => {
|
||||
|
||||
ctx.params = ctx.request.body || ctx.query
|
||||
|
||||
await next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
module.exports = {
|
||||
path : "app/*/api/*.js",
|
||||
prefix : "",//接口前缀
|
||||
statusTobody: true,//是否跟随body结果(如需接口报错也返回200,那么设置为false)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
'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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user