From 6e689c7155445a6bfed05291f72c719268577b23 Mon Sep 17 00:00:00 2001 From: Jonathan Keslin Date: Thu, 17 Sep 2020 14:17:41 -0700 Subject: [PATCH] fix(serverless): gracefully fail with 400 for null body (#38) --- index.js | 8 ++++++++ tests/index.test.js | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/index.js b/index.js index a8ebbb6..f34a009 100644 --- a/index.js +++ b/index.js @@ -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) { diff --git a/tests/index.test.js b/tests/index.test.js index 6935575..a2e3776 100644 --- a/tests/index.test.js +++ b/tests/index.test.js @@ -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() + }) })