UNPKG

1.83 kBJavaScriptView Raw
1'use strict';
2
3const http = require('http');
4const https = require('https');
5const url = require('url');
6// By default tailor supports gzipped response from fragments
7const requiredHeaders = {
8 'accept-encoding': 'gzip, deflate'
9};
10
11/**
12 * Simple Request Promise Function that requests the fragment server with
13 * - filtered headers
14 * - Specified timeout from fragment attributes
15 *
16 * @param {filterHeaders} - Function that handles the header forwarding
17 * @param {string} fragmentUrl - URL of the fragment server
18 * @param {Object} fragmentAttributes - Attributes passed via fragment tags
19 * @param {Object} request - HTTP request stream
20 * @returns {Promise} Response from the fragment server
21 */
22module.exports = filterHeaders => (fragmentUrl, fragmentAttributes, request) =>
23 new Promise((resolve, reject) => {
24 const parsedUrl = url.parse(fragmentUrl);
25 const options = Object.assign(
26 {
27 headers: Object.assign(
28 filterHeaders(fragmentAttributes, request),
29 requiredHeaders
30 ),
31 keepAlive: true,
32 timeout: fragmentAttributes.timeout
33 },
34 parsedUrl
35 );
36 const { protocol: reqProtocol, timeout } = options;
37 const protocol = reqProtocol === 'https:' ? https : http;
38 const fragmentRequest = protocol.request(options);
39 if (timeout) {
40 fragmentRequest.setTimeout(timeout, fragmentRequest.abort);
41 }
42 fragmentRequest.on('response', response => {
43 if (response.statusCode >= 500) {
44 reject(new Error('Internal Server Error'));
45 } else {
46 resolve(response);
47 }
48 });
49 fragmentRequest.on('error', reject);
50 fragmentRequest.end();
51 });