overleaf/services/web/app/src/infrastructure/BodyParserWrapper.js
Miguel Serrano 42c917d909 Merge pull request #3046 from overleaf/msm-cleanup-oerror-http
Finish o-error/http cleanup

GitOrigin-RevId: 1f8cf7f1e0503d1071c51b41ac136f7fb7f38872
2020-08-12 02:06:53 +00:00

35 lines
803 B
JavaScript

const bodyParser = require('body-parser')
const HttpErrorHandler = require('../Features/Errors/HttpErrorHandler')
function isBodyParserError(nextArg) {
if (nextArg instanceof Error) {
return (
nextArg.statusCode &&
nextArg.statusCode >= 400 &&
nextArg.statusCode < 600
)
}
return false
}
const wrapBodyParser = method => opts => {
const middleware = bodyParser[method](opts)
return (req, res, next) => {
middleware(req, res, nextArg => {
if (isBodyParserError(nextArg)) {
return HttpErrorHandler.handleErrorByStatusCode(
req,
res,
nextArg,
nextArg.statusCode
)
}
next(nextArg)
})
}
}
module.exports = {
urlencoded: wrapBodyParser('urlencoded'),
json: wrapBodyParser('json')
}