@middy/http-json-body-parser
Advanced tools
Comparing version 1.0.0-alpha.4 to 1.0.0-alpha.5
@@ -24,2 +24,21 @@ const middy = require('../../core') | ||
test('It should parse a JSON request with lowercase header', () => { | ||
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', () => { | ||
@@ -26,0 +45,0 @@ const handler = middy((event, context, cb) => { |
17
index.js
@@ -6,9 +6,12 @@ const createError = require('http-errors') | ||
before: (handler, next) => { | ||
if (handler.event.headers && handler.event.headers['Content-Type']) { | ||
const { type } = contentType.parse(handler.event.headers['Content-Type']) | ||
if (type === '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') | ||
if (handler.event.headers) { | ||
const contentTypeHeader = handler.event.headers['content-type'] || handler.event.headers['Content-Type'] | ||
if (contentTypeHeader) { | ||
const { type } = contentType.parse(contentTypeHeader) | ||
if (type === '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') | ||
} | ||
} | ||
@@ -15,0 +18,0 @@ } |
{ | ||
"name": "@middy/http-json-body-parser", | ||
"version": "1.0.0-alpha.4", | ||
"version": "1.0.0-alpha.5", | ||
"description": "Http JSON body parser middleware for the middy framework", | ||
@@ -5,0 +5,0 @@ "engines": { |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
9005
145