Skip to content

Commit

Permalink
fix(serverless): gracefully fail with 400 for null body (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
decompil3d authored Sep 17, 2020
1 parent b2cee55 commit 6e689c7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ module.exports.serverless = appFn => {
// Convert the payload to an Object if API Gateway stringifies it
event.body = (typeof event.body === 'string') ? JSON.parse(event.body) : event.body

// Bail for null body
if (!event.body) {
return context.done(null, {
statusCode: 400,
body: 'Event body is null.'
})
}

// Do the thing
console.log(`Received event ${e}${event.body.action ? ('.' + event.body.action) : ''}`)
if (event) {
Expand Down
16 changes: 16 additions & 0 deletions tests/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,20 @@ describe('serverless-lambda', () => {
expect(context.done).toHaveBeenCalled()
expect(spy).toHaveBeenCalled()
})

it('responds with a 400 error when body is null', async () => {
const event = {
body: null,
headers: {
'X-Github-Event': 'issues',
'x-github-delivery': 123
}
}

await handler(event, context)
expect(context.done).toHaveBeenCalledWith(null, expect.objectContaining({
statusCode: 400
}))
expect(spy).not.toHaveBeenCalled()
})
})

0 comments on commit 6e689c7

Please sign in to comment.