2020-03-09 09:36:13 -04:00
|
|
|
const bodyParser = require('body-parser')
|
2020-08-11 05:12:49 -04:00
|
|
|
const HttpErrorHandler = require('../Features/Errors/HttpErrorHandler')
|
2020-03-09 09:36:13 -04:00
|
|
|
|
2020-08-11 05:12:49 -04:00
|
|
|
function isBodyParserError(nextArg) {
|
|
|
|
if (nextArg instanceof Error) {
|
|
|
|
return (
|
|
|
|
nextArg.statusCode &&
|
|
|
|
nextArg.statusCode >= 400 &&
|
|
|
|
nextArg.statusCode < 600
|
|
|
|
)
|
2020-03-09 09:36:13 -04:00
|
|
|
}
|
2020-08-11 05:12:49 -04:00
|
|
|
return false
|
2020-03-09 09:36:13 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const wrapBodyParser = method => opts => {
|
|
|
|
const middleware = bodyParser[method](opts)
|
|
|
|
return (req, res, next) => {
|
|
|
|
middleware(req, res, nextArg => {
|
2020-08-11 05:12:49 -04:00
|
|
|
if (isBodyParserError(nextArg)) {
|
|
|
|
return HttpErrorHandler.handleErrorByStatusCode(
|
|
|
|
req,
|
|
|
|
res,
|
|
|
|
nextArg,
|
|
|
|
nextArg.statusCode
|
|
|
|
)
|
2020-03-09 09:36:13 -04:00
|
|
|
}
|
|
|
|
next(nextArg)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
urlencoded: wrapBodyParser('urlencoded'),
|
|
|
|
json: wrapBodyParser('json')
|
|
|
|
}
|