-
-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathindex.js
More file actions
56 lines (48 loc) · 1.51 KB
/
index.js
File metadata and controls
56 lines (48 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright 2017 - 2026 will Farrell, Luciano Mammino, and Middy contributors.
// SPDX-License-Identifier: MIT
import { createError, decodeBody } from "@middy/util";
const jsonContentTypePattern = /^application\/([a-z0-9.+-]+\+)?json(;|$)/i;
const defaults = {
reviver: undefined,
disableContentTypeCheck: false,
disableContentTypeError: false,
};
const httpJsonBodyParserMiddleware = (opts = {}) => {
const options = { ...defaults, ...opts };
const httpJsonBodyParserMiddlewareBefore = (request) => {
const { headers, body } = request.event;
const contentType = headers?.["content-type"] ?? headers?.["Content-Type"];
if (
!options.disableContentTypeCheck &&
!jsonContentTypePattern.test(contentType)
) {
if (options.disableContentTypeError) {
return;
}
throw createError(415, "Unsupported Media Type", {
cause: { package: "@middy/http-json-body-parser", data: contentType },
});
}
if (typeof body === "undefined") {
throw createError(422, "Invalid or malformed JSON was provided", {
cause: { package: "@middy/http-json-body-parser", data: body },
});
}
try {
const data = decodeBody(request.event);
request.event.body = JSON.parse(data, options.reviver);
} catch (err) {
throw createError(422, "Invalid or malformed JSON was provided", {
cause: {
package: "@middy/http-json-body-parser",
data: body,
message: err.message,
},
});
}
};
return {
before: httpJsonBodyParserMiddlewareBefore,
};
};
export default httpJsonBodyParserMiddleware;