-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrequest-fragment.js
85 lines (75 loc) · 2.73 KB
/
request-fragment.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
const http = require('http');
const https = require('https');
const url = require('url');
const Agent = require('agentkeepalive');
const HttpsAgent = require('agentkeepalive').HttpsAgent;
const { globalTracer, FORMAT_HTTP_HEADERS } = require('opentracing');
const tracer = globalTracer();
// By default tailor supports gzipped response from fragments
const requiredHeaders = {
'accept-encoding': 'gzip, deflate'
};
const kaAgent = new Agent();
const kaAgentHttps = new HttpsAgent();
/**
* Simple Request Promise Function that requests the fragment server with
* - filtered headers
* - Specified timeout from fragment attributes
*
* @param {filterHeaders} - Function that handles the header forwarding
* @param {processFragmentResponse} - Function that handles response processing
* @param {string} fragmentUrl - URL of the fragment server
* @param {Object} fragmentAttributes - Attributes passed via fragment tags
* @param {Object} request - HTTP request stream
* @param {Object} span - opentracing span context passed for propagation
* @returns {Promise} Response from the fragment server
*/
module.exports = (filterHeaders, processFragmentResponse) => (
fragmentUrl,
fragmentAttributes,
request,
span = null
) =>
new Promise((resolve, reject) => {
const parsedUrl = url.parse(fragmentUrl);
const options = Object.assign(
{
headers: Object.assign(
filterHeaders(fragmentAttributes, request),
requiredHeaders
),
timeout: fragmentAttributes.timeout
},
parsedUrl
);
if (span) {
tracer.inject(span.context(), FORMAT_HTTP_HEADERS, options.headers);
}
const { protocol: reqProtocol, timeout } = options;
const hasHttpsProtocol = reqProtocol === 'https:';
const protocol = hasHttpsProtocol ? https : http;
options.agent = hasHttpsProtocol ? kaAgentHttps : kaAgent;
if (hasHttpsProtocol && fragmentAttributes.ignoreInvalidSsl) {
options.rejectUnauthorized = false;
}
const fragmentRequest = protocol.request(options);
if (timeout) {
fragmentRequest.setTimeout(timeout, fragmentRequest.abort);
}
fragmentRequest.on('response', response => {
try {
resolve(
processFragmentResponse(response, {
request,
fragmentUrl,
fragmentAttributes
})
);
} catch (e) {
reject(e);
}
});
fragmentRequest.on('error', reject);
fragmentRequest.end();
});