Skip to content

Commit 6e689c7

Browse files
authored
fix(serverless): gracefully fail with 400 for null body (#38)
1 parent b2cee55 commit 6e689c7

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

index.js

+8
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,14 @@ module.exports.serverless = appFn => {
5757
// Convert the payload to an Object if API Gateway stringifies it
5858
event.body = (typeof event.body === 'string') ? JSON.parse(event.body) : event.body
5959

60+
// Bail for null body
61+
if (!event.body) {
62+
return context.done(null, {
63+
statusCode: 400,
64+
body: 'Event body is null.'
65+
})
66+
}
67+
6068
// Do the thing
6169
console.log(`Received event ${e}${event.body.action ? ('.' + event.body.action) : ''}`)
6270
if (event) {

tests/index.test.js

+16
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,20 @@ describe('serverless-lambda', () => {
3434
expect(context.done).toHaveBeenCalled()
3535
expect(spy).toHaveBeenCalled()
3636
})
37+
38+
it('responds with a 400 error when body is null', async () => {
39+
const event = {
40+
body: null,
41+
headers: {
42+
'X-Github-Event': 'issues',
43+
'x-github-delivery': 123
44+
}
45+
}
46+
47+
await handler(event, context)
48+
expect(context.done).toHaveBeenCalledWith(null, expect.objectContaining({
49+
statusCode: 400
50+
}))
51+
expect(spy).not.toHaveBeenCalled()
52+
})
3753
})

0 commit comments

Comments
 (0)