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