@middy/http-json-body-parser
Advanced tools
Comparing version 1.0.0-alpha.30 to 1.0.0-alpha.31
@@ -24,2 +24,23 @@ const middy = require('../../core') | ||
test('It should use a reviver when parsing a JSON request', () => { | ||
const handler = middy((event, context, cb) => { | ||
cb(null, event.body) // propagates the body as a response | ||
}) | ||
const reviver = _ => _ | ||
handler.use(jsonBodyParser({ reviver })) | ||
// invokes the handler | ||
const event = { | ||
headers: { | ||
'Content-Type': 'application/json' | ||
}, | ||
body: JSON.stringify({ foo: 'bar' }) | ||
} | ||
const parse = jest.spyOn(JSON, 'parse') | ||
handler(event, {}, (_, body) => { | ||
expect(parse).toHaveBeenCalledWith(event.body, reviver) | ||
}) | ||
parse.mockRestore() | ||
}) | ||
test('It should parse a JSON request with lowercase header', () => { | ||
@@ -26,0 +47,0 @@ const handler = middy((event, context, cb) => { |
import middy from '../core' | ||
declare function jsonBodyParser(): middy.IMiddyMiddlewareObject; | ||
interface IJsonBodyParserOptions { | ||
reviver?: (key: string, value: any) => any | ||
} | ||
declare function jsonBodyParser(opts: IJsonBodyParserOptions): middy.IMiddyMiddlewareObject; | ||
export default jsonBodyParser |
const createError = require('http-errors') | ||
const contentType = require('content-type') | ||
module.exports = () => ({ | ||
module.exports = (opts) => ({ | ||
before: (handler, next) => { | ||
opts = opts || {} | ||
if (handler.event.headers) { | ||
@@ -12,3 +13,3 @@ const contentTypeHeader = handler.event.headers['content-type'] || handler.event.headers['Content-Type'] | ||
try { | ||
handler.event.body = JSON.parse(handler.event.body) | ||
handler.event.body = JSON.parse(handler.event.body, opts.reviver) | ||
} catch (err) { | ||
@@ -15,0 +16,0 @@ throw new createError.UnprocessableEntity('Content type defined as JSON but an invalid JSON was provided') |
{ | ||
"name": "@middy/http-json-body-parser", | ||
"version": "1.0.0-alpha.30", | ||
"version": "1.0.0-alpha.31", | ||
"description": "Http JSON body parser middleware for the middy framework", | ||
@@ -52,3 +52,3 @@ "engines": { | ||
}, | ||
"gitHead": "cfd121b6daceb3bf4c023041443c2fa3b889dd34" | ||
"gitHead": "7386e91d136cdf3e2725de1010e919e34ec87605" | ||
} |
@@ -50,3 +50,3 @@ # Middy http-json-body-parser middleware | ||
This middleware does not have any option | ||
- reviver (function) (optional): A [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Parameters) parameter may be passed which will be used `JSON.parse`ing the body. | ||
@@ -53,0 +53,0 @@ |
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
9629
121