koa-rtapi
Advanced tools
Comparing version 1.1.42 to 1.1.43
63
index.js
'use strict'; | ||
// 返回错误 | ||
const outError = (ctx, result, code) => { | ||
ctx.body = result; | ||
ctx.status = code; | ||
}; | ||
// 获取路由配置 | ||
const getRouterOpt = (path, dir) => { | ||
const arr = path.substr(1).split('/'); | ||
const last = arr.length - 1; | ||
return { | ||
aPath: last < 2 ? null : `../..${dir}${arr.slice(1, last).join('/')}.api.js`, | ||
aName: '$' + (arr[last] || 'index') | ||
} | ||
}; | ||
// 输出Koa的组件 | ||
module.exports = map => { | ||
return async (ctx, next) => { | ||
const path = ctx.path; | ||
const router = map.find(n => path.indexOf(n.path) === 0); | ||
if (router !== undefined) { | ||
// 解析 | ||
const { aPath, aName } = getRouterOpt(path, router.dir); | ||
if (aPath === null) { | ||
return outError(ctx, `未能解析网址|${path}`, 404); | ||
} | ||
// 控制器 | ||
let api; | ||
try { | ||
const Api = require(aPath); | ||
api = new Api(ctx); | ||
} catch (e) { | ||
return outError(ctx, `控制器错误|${e.message}|${e.stack}`, 500); | ||
} | ||
// 方法 | ||
const method = api[aName]; | ||
if (method === undefined) { | ||
return outError(ctx, `没有找到方法|${aName}`, 404); | ||
} | ||
// 执行API | ||
const body = ctx.method === 'GET' ? ctx.query : ctx.request.body; | ||
try { | ||
api.ctx = ctx; | ||
ctx.body = await method.call(api, body); | ||
} catch (e) { | ||
return outError(ctx, `执行时出错|${e.message}|${e.stack}`, 500); | ||
} | ||
} | ||
await next(); | ||
}; | ||
}; | ||
module.exports = { | ||
router: require('./lib/router') | ||
} |
{ | ||
"name": "koa-rtapi", | ||
"version": "1.1.42", | ||
"version": "1.1.43", | ||
"description": "koa api in rtworld company", | ||
"main": "index.js", | ||
"bin": { | ||
"koa-rtapi-init": "./_bin_init.js" | ||
"koa-rtapi-init": "./init_code.js" | ||
}, | ||
@@ -9,0 +9,0 @@ "scripts": { |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
5186
9
122
1