|
1 |
| -const url = require("url"); |
| 1 | +const http = require("http"); |
| 2 | +const https = require("https"); |
| 3 | +const { parse } = require("url"); |
2 | 4 |
|
3 |
| -function loadFromHttp(pathToSpec, { auth }) { |
4 |
| - const { protocol } = url.parse(pathToSpec); |
5 |
| - |
6 |
| - if (protocol !== "http:" && protocol !== "https:") { |
7 |
| - throw new Error(`Unsupported protocol: "${protocol}". URL must start with "http://" or "https://".`); |
8 |
| - } |
| 5 | +// config |
| 6 | +const MAX_REDIRECT_COUNT = 10; |
9 | 7 |
|
10 |
| - const fetch = require(protocol === "https:" ? "https" : "http"); |
| 8 | +function fetch(url, opts, { redirectCount = 0 } = {}) { |
11 | 9 | return new Promise((resolve, reject) => {
|
12 |
| - const req = fetch.request( |
13 |
| - pathToSpec, |
14 |
| - { |
15 |
| - method: "GET", |
16 |
| - auth, |
17 |
| - }, |
18 |
| - (res) => { |
19 |
| - let rawData = ""; |
20 |
| - res.setEncoding("utf8"); |
21 |
| - res.on("data", (chunk) => { |
22 |
| - rawData += chunk; |
23 |
| - }); |
24 |
| - res.on("end", () => { |
25 |
| - if (res.statusCode >= 200 && res.statusCode < 300) { |
26 |
| - resolve(rawData); |
27 |
| - } else { |
28 |
| - reject(rawData || `${res.statusCode} ${res.statusMessage}`); |
| 10 | + const { protocol } = parse(url); |
| 11 | + |
| 12 | + if (protocol !== "http:" && protocol !== "https:") { |
| 13 | + throw new Error(`Unsupported protocol: "${protocol}". URL must start with "http://" or "https://".`); |
| 14 | + } |
| 15 | + |
| 16 | + const fetchMethod = protocol === "https:" ? https : http; |
| 17 | + const req = fetchMethod.request(url, opts, (res) => { |
| 18 | + let rawData = ""; |
| 19 | + res.setEncoding("utf8"); |
| 20 | + res.on("data", (chunk) => { |
| 21 | + rawData += chunk; |
| 22 | + }); |
| 23 | + res.on("end", () => { |
| 24 | + // 2xx: OK |
| 25 | + if (res.statusCode >= 200 && res.statusCode < 300) { |
| 26 | + return resolve(rawData); |
| 27 | + } |
| 28 | + |
| 29 | + // 3xx: follow redirect (if given) |
| 30 | + if (res.statusCode >= 300 && res.headers.location) { |
| 31 | + redirectCount += 1; |
| 32 | + if (redirectCount >= MAX_REDIRECT_COUNT) { |
| 33 | + reject(`Max redirects exceeded`); |
| 34 | + return; |
29 | 35 | }
|
30 |
| - }); |
31 |
| - } |
32 |
| - ); |
| 36 | + console.log(`🚥 Redirecting to ${res.headers.location}…`); |
| 37 | + return fetch(res.headers.location, opts).then(resolve); |
| 38 | + } |
| 39 | + |
| 40 | + // everything else: throw |
| 41 | + return reject(rawData || `${res.statusCode} ${res.statusMessage}`); |
| 42 | + }); |
| 43 | + }); |
33 | 44 | req.on("error", (err) => {
|
34 | 45 | reject(err);
|
35 | 46 | });
|
36 | 47 | req.end();
|
37 | 48 | });
|
38 | 49 | }
|
| 50 | + |
| 51 | +function loadFromHttp(pathToSpec, { auth }) { |
| 52 | + return fetch(pathToSpec, { method: "GET", auth }); |
| 53 | +} |
39 | 54 | module.exports = loadFromHttp;
|
0 commit comments