Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse json body when content-type header is lower-cased #75

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/middlewares/__tests__/jsonBodyParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,25 @@ describe('📦 Middleware JSON Body Parser', () => {
})
})

test('It should parse a JSON request when header key is lower-cased', () => {
const handler = middy((event, context, cb) => {
cb(null, event.body) // propagates the body as a response
})

handler.use(jsonBodyParser())

// invokes the handler
const event = {
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({foo: 'bar'})
}
handler(event, {}, (_, body) => {
expect(body).toEqual({foo: 'bar'})
})
})

test('It should handle invalid JSON as an UnprocessableEntity', () => {
const handler = middy((event, context, cb) => {
cb(null, event.body) // propagates the body as a response
Expand Down
6 changes: 5 additions & 1 deletion src/middlewares/jsonBodyParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@ const createError = require('http-errors')

module.exports = () => ({
before: (handler, next) => {
if (handler.event.headers && handler.event.headers['Content-Type'] === 'application/json') {
const headers = handler.event.headers || {}
const contentType = headers['Content-Type'] || headers['content-type']

if (contentType === 'application/json') {
try {
handler.event.body = JSON.parse(handler.event.body)
} catch (err) {
throw new createError.UnprocessableEntity('Content type defined as JSON but an invalid JSON was provided')
}
}

next()
}
})