1 | "use strict";
|
2 |
|
3 | const {
|
4 | normalizeHttpResponse
|
5 | } = require('@middy/util');
|
6 |
|
7 | const Accept = require('@hapi/accept');
|
8 |
|
9 | const defaults = {
|
10 | serializers: [],
|
11 | default: undefined
|
12 | };
|
13 |
|
14 | const httpResponseSerializerMiddleware = (opts = {}) => {
|
15 | const options = { ...defaults,
|
16 | ...opts
|
17 | };
|
18 |
|
19 | const httpResponseSerializerMiddlewareAfter = async request => {
|
20 | var _request$event;
|
21 |
|
22 | if (request.response === undefined) return;
|
23 | request.response = normalizeHttpResponse(request.response);
|
24 |
|
25 | if (request.response.headers['Content-Type'] || request.response.headers['content-type']) {
|
26 | return;
|
27 | }
|
28 |
|
29 |
|
30 | let types;
|
31 |
|
32 | if ((_request$event = request.event) !== null && _request$event !== void 0 && _request$event.requiredContentType) {
|
33 | types = [request.event.requiredContentType];
|
34 | } else {
|
35 | var _request$event$header, _request$event2, _request$event2$heade, _request$event3, _request$event3$heade, _ref;
|
36 |
|
37 | const acceptHeader = (_request$event$header = (_request$event2 = request.event) === null || _request$event2 === void 0 ? void 0 : (_request$event2$heade = _request$event2.headers) === null || _request$event2$heade === void 0 ? void 0 : _request$event2$heade.accept) !== null && _request$event$header !== void 0 ? _request$event$header : (_request$event3 = request.event) === null || _request$event3 === void 0 ? void 0 : (_request$event3$heade = _request$event3.headers) === null || _request$event3$heade === void 0 ? void 0 : _request$event3$heade.Accept;
|
38 | types = [...((_ref = acceptHeader && Accept.mediaTypes(acceptHeader)) !== null && _ref !== void 0 ? _ref : []), request.event.preferredContentType, options.default];
|
39 | }
|
40 |
|
41 | for (const type of types) {
|
42 | let breakTypes;
|
43 |
|
44 | for (const s of options.serializers) {
|
45 | if (!s.regex.test(type)) {
|
46 | continue;
|
47 | }
|
48 |
|
49 | request.response.headers['Content-Type'] = type;
|
50 | const result = s.serializer(request.response);
|
51 |
|
52 | if (typeof result === 'object' && 'body' in result) {
|
53 | request.response = result;
|
54 | } else {
|
55 |
|
56 | request.response.body = result;
|
57 | }
|
58 |
|
59 | breakTypes = true;
|
60 | break;
|
61 | }
|
62 |
|
63 | if (breakTypes) break;
|
64 | }
|
65 | };
|
66 |
|
67 | const httpResponseSerializerMiddlewareOnError = httpResponseSerializerMiddlewareAfter;
|
68 | return {
|
69 | after: httpResponseSerializerMiddlewareAfter,
|
70 | onError: httpResponseSerializerMiddlewareOnError
|
71 | };
|
72 | };
|
73 |
|
74 | module.exports = httpResponseSerializerMiddleware;
|