UNPKG

2.04 kBJavaScriptView Raw
1import { normalizeHttpResponse } from '@middy/util';
2import Accept from '@hapi/accept';
3const defaults = {
4 serializers: [],
5 defaultContentType: undefined
6};
7const httpResponseSerializerMiddleware = (opts = {})=>{
8 const { serializers , defaultContentType } = {
9 ...defaults,
10 ...opts
11 };
12 const httpResponseSerializerMiddlewareAfter = async (request)=>{
13 normalizeHttpResponse(request);
14 if (request.response.headers['Content-Type']) return;
15 let types;
16 if (request.event.requiredContentType) {
17 types = [
18 request.event.requiredContentType
19 ];
20 } else {
21 const acceptHeader = request.event.headers.Accept ?? request.event.headers.accept;
22 types = [
23 ...(acceptHeader && Accept.mediaTypes(acceptHeader)) ?? [],
24 request.event.preferredContentType,
25 defaultContentType
26 ];
27 }
28 for (const type of types){
29 let breakTypes;
30 for (const s of serializers){
31 if (!s.regex.test(type)) {
32 continue;
33 }
34 request.response.headers['Content-Type'] = type;
35 const result = s.serializer(request.response);
36 if (typeof result === 'object' && 'body' in result) {
37 request.response = result;
38 } else {
39 request.response.body = result;
40 }
41 breakTypes = true;
42 break;
43 }
44 if (breakTypes) break;
45 }
46 };
47 const httpResponseSerializerMiddlewareOnError = async (request)=>{
48 if (request.response === undefined) return;
49 return httpResponseSerializerMiddlewareAfter(request);
50 };
51 return {
52 after: httpResponseSerializerMiddlewareAfter,
53 onError: httpResponseSerializerMiddlewareOnError
54 };
55};
56export default httpResponseSerializerMiddleware;
57
58
59//# sourceMappingURL=index.js.map
\No newline at end of file