UNPKG

1.56 kBJavaScriptView Raw
1// @flow
2
3import type { Response } from '../types/Responses';
4
5/**
6 * @classdesc
7 * Holds common methods for the different responses mergers.
8 *
9 * @class
10 * ResponseMergerBase
11 *
12 * @abstract
13 */
14module.exports = class ResponseMergerBase {
15 /**
16 * Carriage return line feed.
17 *
18 * @return {string}
19 * The string.
20 */
21 static getCrlf(): string {
22 return '\r\n';
23 }
24
25 /**
26 * Clean a response to a subrequest.
27 *
28 * @param {Response} response
29 * The response to clean.
30 *
31 * @return {Response}
32 * The clean response.
33 *
34 * @private
35 */
36 static _cleanResponse(response: Response): Response {
37 response.body = response.body.replace(new RegExp(`${this.getCrlf()}$`), '');
38 return response;
39 }
40
41 /**
42 * Negotiates the sub Content-Type.
43 *
44 * Checks if all responses have the same Content-Type header. If they do, then
45 * it returns that one. If not, it defaults to 'application/json'.
46 *
47 * @param {Response[]} responses
48 * The responses.
49 *
50 * @return {string}
51 * The collective content type. 'application/json' if no conciliation is
52 * possible.
53 *
54 * @private
55 */
56 static _negotiateSubContentType(responses: Array<Response>): string {
57 let output = null;
58 responses.forEach((response) => {
59 const ct = response.headers.get('Content-Type') || response.headers.get('content-type');
60 if (output === null) {
61 output = ct;
62 }
63 if (output !== ct) {
64 output = 'application/json';
65 }
66 });
67 return output || 'application/json';
68 }
69};