app-lib-mock-server-parse
Version:
body解析-【app-lib-mock-server-parse】
96 lines (84 loc) • 3.13 kB
JavaScript
/*************************************************************************************
*
* 动态解析或者指定解析方式
*
* 1. 当前系统存在多种或一种解析方式 往往一种不一定能满足需求 故自动解析
* 2. 动态根据contenttype + body内容合法性校验 进行解析
* 3. 可在插件中间件中prase进行配置
*
*
**************************************************************************************/
/*************************************************************************************
*
* 动态解析或者指定解析方式
*
*
* 1.中间件配置
*
* ```
* "params":{
* "paraseType":"text",
* // 解析类型 text 文件 json json格式 raw raw格式 后续有需要自定义该插件
* }
* ```
*
*
**************************************************************************************/
/*************************************************************************************
*
* 改造body-parser
*
* 扩展
* 1. 原有的解析 一个解析失败后 另个不能在解析 针对json类型需要text解析的情况
*
*
**************************************************************************************/
const PARSER = require("./body-parser/index");
const middwareName = "MIDDWARE_PARSE"
// stream 读过一次不能再读--TODO 先用json 自用其他?
const myNext = (req, next, type, log) => {
return (error) => {
if (error) {
req._body = undefined; // 清空内部解析记录 继续下一个解析
log.md(middwareName, `${type} parse error`, error.type, error.message)
} else {
if (!req.__parse) {
req.__parse = type;
}
}
next();
}
}
// https://github.com/expressjs/body-parser
const bodyParser = (parseOpt, type) => {
let { option: { log: { log } } } = Frame;
return (req, res, next) => {
// 设置强制解析
if (parseOpt.forceParse) {
req.__forceParse = type;
}
PARSER[type](parseOpt || {})(req, res, myNext(req, next, type, log))
}
};
const PARSES = {
json: bodyParser,
text: bodyParser,
raw: bodyParser,
urlencoded: bodyParser,
// 后续按需扩展
}
const middleware = (middlewareConfig) => {
let { params } = middlewareConfig;
let types = params.paraseType || ["json"]; // 目前支持四种 ["json","raw","text","urlencoded"]
// 按照配置解析顺序进行解析
return types.map(type => {
let parasemiddware = PARSES[type];
if (!parasemiddware) {
log.mwn(middwareName, `current not spport parase [${type}]`);
return null;
} else {
return { position: 'begin', method: "use", alias: type, matchPath: "", middleware: parasemiddware(params[type], type) };
}
}).filter(v => !!v);
}
module.exports = { middleware }