1 |
|
2 |
|
3 | import type { Response, ResponseMergerStaticsInterface } from '../types/Responses';
|
4 |
|
5 | const contentType = require('content-type');
|
6 | const md5 = require('md5');
|
7 | const ResponseMergerBase = require('./ResponseMergerBase');
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | class MultipartRelatedResponse extends ResponseMergerBase {
|
17 | |
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | static mergeResponses(responses: Array<Response>): Response {
|
27 | const delimiter = this._generateDelimiter();
|
28 | const crlf = this.getCrlf();
|
29 | const headers = new Map();
|
30 |
|
31 | headers.set('Status', '207');
|
32 |
|
33 | const ct = contentType.format({
|
34 | type: 'multipart/related',
|
35 | parameters: {
|
36 | boundary: delimiter,
|
37 | type: this._negotiateSubContentType(responses),
|
38 | },
|
39 | });
|
40 |
|
41 | headers.set('Content-Type', ct);
|
42 | const output: Response = {
|
43 | headers,
|
44 | body: '',
|
45 | };
|
46 |
|
47 | const parts = responses
|
48 | .map(this._cleanResponse.bind(this))
|
49 | .map(this.serializeResponse.bind(this));
|
50 |
|
51 |
|
52 | output.body += `${delimiter}--${crlf}`;
|
53 | output.body += parts.join(`${crlf}--${delimiter}${crlf}`);
|
54 | output.body += `${crlf}--${delimiter}--`;
|
55 | return output;
|
56 | }
|
57 |
|
58 | |
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 | static serializeResponse(response: Response): string {
|
70 | let output = '';
|
71 |
|
72 | const crlf = this.getCrlf();
|
73 | response.headers.forEach((value, name) => {
|
74 | output += `${name}: ${value}${crlf}`;
|
75 | });
|
76 |
|
77 | return `${output}${crlf}${response.body}`;
|
78 | }
|
79 |
|
80 | |
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 | static _generateDelimiter(): string {
|
89 | return md5(Date.now()).substr(0, 6);
|
90 | }
|
91 | }
|
92 | (MultipartRelatedResponse: ResponseMergerStaticsInterface);
|
93 |
|
94 | module.exports = MultipartRelatedResponse;
|