| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- /**
- * 查询参数清理中间件
- * 处理查询参数中的字符串"undefined",将其转换为适当的默认值
- */
- const ParamArr=['UserID', 'SchoolID', 'DistrictID', 'ClickLikeID', 'QuestionTypeID', "Style", "Level"];
- export default function queryParamSanitizer() {
- return async (ctx, next) => {
- // 处理查询参数
- if (ctx.query) {
- Object.keys(ctx.query).forEach(key => {
- if (ctx.query[key] === 'undefined') {
- // 数字类型参数默认设为0
- if (ParamArr.includes(key)) {
- ctx.query[key] = 0;
- }
- // 字符串类型参数默认设为空字符串
- else {
- ctx.query[key] = '';
- }
- }
- });
- }
- // 处理请求体参数(如果是JSON或表单数据)
- if (ctx.request.body && typeof ctx.request.body === 'object') {
- Object.keys(ctx.request.body).forEach(key => {
- if (ctx.request.body[key] === 'undefined') {
- // 数字类型参数默认设为0
- if (ParamArr.includes(key)) {
- ctx.request.body[key] = 0;
- }
- // 字符串类型参数默认设为空字符串
- else {
- ctx.request.body[key] = '';
- }
- }
- });
- }
- await next();
- };
- }
|