70 lines
1.8 KiB
JavaScript
70 lines
1.8 KiB
JavaScript
'use strict';
|
|
/**
|
|
* 加载api路由
|
|
* 加载app/api目录下的文件到路由
|
|
*/
|
|
const Router = require('koa-router')
|
|
const config = require("./config")
|
|
// const parameter = require('./parameter');
|
|
// 错误处理
|
|
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
|
|
console.log(url);
|
|
router.all(url, async (ctx, next) => {
|
|
await next();
|
|
const parameter = app.parameter
|
|
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()
|
|
}
|
|
}
|
|
|
|
//是否跟随body结果
|
|
ctx.status = config.statusTobody ? ctx.body.status || 400 : 200
|
|
|
|
})
|
|
})
|
|
//默认根路由
|
|
router.all('/', async (ctx, next) => {
|
|
ctx.body = app.res.success("ok")
|
|
ctx.status = 200
|
|
await next();
|
|
})
|
|
return router
|
|
}
|
|
}
|