1 | import mask from 'json-mask'
|
2 | import { normalizeHttpResponse, jsonSafeParse } from '@middy/util'
|
3 |
|
4 | const defaults = {
|
5 | filteringKeyName: 'fields'
|
6 | }
|
7 |
|
8 | const httpPartialResponseMiddleware = (opts = {}) => {
|
9 | const options = { ...defaults, ...opts }
|
10 | const { filteringKeyName } = options
|
11 |
|
12 | const httpPartialResponseMiddlewareAfter = async (request) => {
|
13 | const fields = request.event?.queryStringParameters?.[filteringKeyName]
|
14 | if (!fields) return
|
15 |
|
16 | normalizeHttpResponse(request)
|
17 | const body = request.response.body
|
18 | const bodyIsString = typeof body === 'string'
|
19 |
|
20 | const parsedBody = jsonSafeParse(body)
|
21 | if (typeof parsedBody !== 'object') return
|
22 |
|
23 | const filteredBody = mask(parsedBody, fields)
|
24 |
|
25 | request.response.body = bodyIsString
|
26 | ? JSON.stringify(filteredBody)
|
27 | : filteredBody
|
28 | }
|
29 |
|
30 | return {
|
31 | after: httpPartialResponseMiddlewareAfter
|
32 | }
|
33 | }
|
34 | export default httpPartialResponseMiddleware
|