@middy/http-json-body-parser 3.0.0-alpha.0 → 3.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +35 -0
  2. package/package.json +7 -5
package/index.js ADDED
@@ -0,0 +1,35 @@
1
+ import { createError } from '@middy/util';
2
+ const mimePattern = /^application\/(.+\+)?json(;.*)?$/;
3
+ const defaults = {
4
+ reviver: undefined
5
+ };
6
+
7
+ const httpJsonBodyParserMiddleware = (opts = {}) => {
8
+ const options = { ...defaults,
9
+ ...opts
10
+ };
11
+
12
+ const httpJsonBodyParserMiddlewareBefore = async request => {
13
+ const {
14
+ headers,
15
+ body
16
+ } = request.event;
17
+ const contentTypeHeader = headers['Content-Type'] ?? headers['content-type'];
18
+
19
+ if (mimePattern.test(contentTypeHeader)) {
20
+ try {
21
+ const data = request.event.isBase64Encoded ? Buffer.from(body, 'base64').toString() : body;
22
+ request.event.rawBody = body;
23
+ request.event.body = JSON.parse(data, options.reviver);
24
+ } catch (e) {
25
+ throw createError(422, 'Content type defined as JSON but an invalid JSON was provided');
26
+ }
27
+ }
28
+ };
29
+
30
+ return {
31
+ before: httpJsonBodyParserMiddlewareBefore
32
+ };
33
+ };
34
+
35
+ export default httpJsonBodyParserMiddleware;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@middy/http-json-body-parser",
3
- "version": "3.0.0-alpha.0",
3
+ "version": "3.0.0-alpha.4",
4
4
  "description": "Http JSON body parser middleware for the middy framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -13,11 +13,13 @@
13
13
  "exports": "./index.js",
14
14
  "types": "index.d.ts",
15
15
  "files": [
16
+ "index.js",
16
17
  "index.d.ts"
17
18
  ],
18
19
  "scripts": {
19
20
  "test": "npm run test:unit",
20
- "test:unit": "ava"
21
+ "test:unit": "ava",
22
+ "test:benchmark": "node __benchmarks__/index.js"
21
23
  },
22
24
  "license": "MIT",
23
25
  "keywords": [
@@ -48,10 +50,10 @@
48
50
  },
49
51
  "homepage": "https://github.com/middyjs/middy#readme",
50
52
  "dependencies": {
51
- "@middy/util": "^3.0.0-alpha.0"
53
+ "@middy/util": "^3.0.0-alpha.4"
52
54
  },
53
55
  "devDependencies": {
54
- "@middy/core": "^3.0.0-alpha.0"
56
+ "@middy/core": "^3.0.0-alpha.4"
55
57
  },
56
- "gitHead": "c533f62841c8a39d061d7b94f30ba178f002c8db"
58
+ "gitHead": "d4bea7f4e21f6a9bbb1f6f6908361169598b9e53"
57
59
  }