forked from middyjs/middy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
34 lines (28 loc) · 974 Bytes
/
index.js
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
const mimePattern = /^application\/(.+\+)?json(;.*)?$/
const defaults = {
reviver: undefined
}
const httpJsonBodyParserMiddleware = (opts = {}) => {
const options = { ...defaults, ...opts }
const httpJsonBodyParserMiddlewareBefore = async (request) => {
const { headers, body } = request.event
const contentTypeHeader =
headers?.['Content-Type'] ?? headers?.['content-type']
if (mimePattern.test(contentTypeHeader)) {
try {
const data = request.event.isBase64Encoded
? Buffer.from(body, 'base64').toString()
: body
request.event.body = JSON.parse(data, options.reviver)
} catch (err) {
const { createError } = require('@middy/util')
// UnprocessableEntity
throw createError(422, 'Content type defined as JSON but an invalid JSON was provided')
}
}
}
return {
before: httpJsonBodyParserMiddlewareBefore
}
}
module.exports = httpJsonBodyParserMiddleware