queryParamSanitizer.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * 查询参数清理中间件
  3. * 处理查询参数中的字符串"undefined",将其转换为适当的默认值
  4. */
  5. const ParamArr=['UserID', 'SchoolID', 'DistrictID', 'ClickLikeID', 'QuestionTypeID', "Style", "Level"];
  6. export default function queryParamSanitizer() {
  7. return async (ctx, next) => {
  8. // 处理查询参数
  9. if (ctx.query) {
  10. Object.keys(ctx.query).forEach(key => {
  11. if (ctx.query[key] === 'undefined') {
  12. // 数字类型参数默认设为0
  13. if (ParamArr.includes(key)) {
  14. ctx.query[key] = 0;
  15. }
  16. // 字符串类型参数默认设为空字符串
  17. else {
  18. ctx.query[key] = '';
  19. }
  20. }
  21. });
  22. }
  23. // 处理请求体参数(如果是JSON或表单数据)
  24. if (ctx.request.body && typeof ctx.request.body === 'object') {
  25. Object.keys(ctx.request.body).forEach(key => {
  26. if (ctx.request.body[key] === 'undefined') {
  27. // 数字类型参数默认设为0
  28. if (ParamArr.includes(key)) {
  29. ctx.request.body[key] = 0;
  30. }
  31. // 字符串类型参数默认设为空字符串
  32. else {
  33. ctx.request.body[key] = '';
  34. }
  35. }
  36. });
  37. }
  38. await next();
  39. };
  40. }