更新
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
module.exports = {
|
||||
path : "app/*/api/*.js",
|
||||
prefix : "",//接口前缀
|
||||
statusTobody: true,//是否跟随body结果(如需接口报错也返回200,那么设置为false)
|
||||
statusTobody: false,//是否跟随body结果(如需接口报错也返回200,那么设置为false)
|
||||
}
|
||||
|
||||
+37
-17
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
const Router = require('koa-router')
|
||||
const config = require("./config")
|
||||
|
||||
// const parameter = require('./parameter');
|
||||
// 错误处理
|
||||
module.exports = {
|
||||
sort : 999, //排序
|
||||
@@ -15,36 +15,56 @@ module.exports = {
|
||||
app.use(router.routes()).use(router.allowedMethods())
|
||||
},
|
||||
fun : async (app) => {
|
||||
const parameter = app.parameter
|
||||
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
|
||||
console.log(url);
|
||||
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()
|
||||
}
|
||||
await next();
|
||||
const validate = parameter.validate(item.res.params, ctx.params);
|
||||
let res = null
|
||||
if (validate) {
|
||||
ctx.body = app.res.error(validate, "参数验证不通过", 204)
|
||||
} else {
|
||||
/*处理body结果*/
|
||||
try {
|
||||
res = await item.res.fun(ctx, app)
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
ctx.body = app.res.error(null, "系统错误", 500)
|
||||
}
|
||||
}
|
||||
|
||||
if (!ctx.body) {
|
||||
if (res) {
|
||||
if (res.status&&res.message) {
|
||||
ctx.body = res
|
||||
}else{
|
||||
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();
|
||||
|
||||
})
|
||||
})
|
||||
|
||||
router.all('/', async (ctx, next) => {
|
||||
|
||||
ctx.body = app.res.success("ok")
|
||||
ctx.status = 200
|
||||
await next();
|
||||
})
|
||||
return router
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
const Parameter = require('parameter');
|
||||
const parameter = new Parameter();
|
||||
|
||||
//添加规则
|
||||
// parameter.addRule('123', (rule, value) => {
|
||||
// if (value !== '123') {
|
||||
// return 'must be 123';
|
||||
// }
|
||||
// });
|
||||
|
||||
module.exports = parameter
|
||||
Reference in New Issue
Block a user