BodyParserWrapper.js 804 B

1234567891011121314151617181920212223242526272829303132333435
  1. const bodyParser = require('body-parser')
  2. const HttpErrorHandler = require('../Features/Errors/HttpErrorHandler')
  3. function isBodyParserError(nextArg) {
  4. if (nextArg instanceof Error) {
  5. return (
  6. nextArg.statusCode &&
  7. nextArg.statusCode >= 400 &&
  8. nextArg.statusCode < 600
  9. )
  10. }
  11. return false
  12. }
  13. const wrapBodyParser = method => opts => {
  14. const middleware = bodyParser[method](opts)
  15. return (req, res, next) => {
  16. middleware(req, res, nextArg => {
  17. if (isBodyParserError(nextArg)) {
  18. return HttpErrorHandler.handleErrorByStatusCode(
  19. req,
  20. res,
  21. nextArg,
  22. nextArg.statusCode
  23. )
  24. }
  25. next(nextArg)
  26. })
  27. }
  28. }
  29. module.exports = {
  30. urlencoded: wrapBodyParser('urlencoded'),
  31. json: wrapBodyParser('json'),
  32. }