|
1 | | -import http from 'http'; |
2 | | -import https from 'https'; |
3 | | - |
4 | | -const MAX_REDIRECTS = 30; |
5 | | - |
6 | | -const fetchUrl = (url, headers = {}, redirectCount = 0) => { |
7 | | - if (redirectCount >= MAX_REDIRECTS) { |
8 | | - return new Promise((_, reject) => { |
9 | | - reject(new Error(`Too many redirects (limit: ${MAX_REDIRECTS})`)); |
10 | | - }); |
11 | | - } |
12 | | - return new Promise((resolve, reject) => { |
13 | | - const parsedUrl = new URL(url); |
14 | | - const h = (parsedUrl.protocol === 'https:') ? https : http; |
15 | | - let options = { |
16 | | - headers: headers |
17 | | - }; |
18 | | - |
19 | | - h.get(url, options, res => { |
20 | | - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { // redirect url |
21 | | - res.resume(); |
22 | | - |
23 | | - fetchUrl(res.headers.location, {}, redirectCount + 1).then(buffer => { |
24 | | - resolve(buffer); |
25 | | - }, result => { |
26 | | - reject(result); |
27 | | - }); |
28 | | - return; |
29 | | - } |
30 | | - |
31 | | - const ok = res.statusCode >= 200 && res.statusCode < 300; |
32 | | - if (!ok) { |
33 | | - reject(new TypeError(`Failed to fetch (status code: ${res.statusCode}, url: "${url}")`)); |
34 | | - res.resume(); |
35 | | - return; |
| 1 | +const fetchUrl = (url, headers = {}) => { |
| 2 | + return fetch(url, { headers }).then( |
| 3 | + response => { |
| 4 | + if (!response.ok) { |
| 5 | + throw new TypeError(`Failed to fetch (status code: ${response.status}, url: "${url}")`); |
36 | 6 | } |
37 | | - |
38 | | - const chunks = []; |
39 | | - res.on('end', () => resolve(Buffer.concat(chunks))); |
40 | | - res.on('data', d => chunks.push(d)); |
41 | | - }).on('error', reject); |
42 | | - }); |
| 7 | + return response.arrayBuffer(); |
| 8 | + }, |
| 9 | + () => { |
| 10 | + throw new TypeError(`Network request failed (url: "${url}")`); |
| 11 | + } |
| 12 | + ); |
43 | 13 | }; |
44 | 14 |
|
45 | 15 | class URLResolver { |
|
0 commit comments