(url, options_)
| 69 | * @return {Promise<import('./response').default>} |
| 70 | */ |
| 71 | export default async function fetch(url, options_) { |
| 72 | return new Promise((resolve, reject) => { |
| 73 | // Build request object |
| 74 | const request = new Request(url, options_); |
| 75 | const { parsedURL, options } = getNodeRequestOptions(request); |
| 76 | if (!supportedSchemas.has(parsedURL.protocol)) { |
| 77 | throw new TypeError( |
| 78 | `node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`, |
| 79 | ); |
| 80 | } |
| 81 | |
| 82 | if (parsedURL.protocol === "data:") { |
| 83 | const data = dataUriToBuffer(request.url); |
| 84 | const response = new Response(data, { |
| 85 | headers: { "Content-Type": data.typeFull }, |
| 86 | }); |
| 87 | resolve(response); |
| 88 | return; |
| 89 | } |
| 90 | |
| 91 | // Wrap http.request into fetch |
| 92 | const send = (parsedURL.protocol === "https:" ? https : http).request; |
| 93 | const { signal } = request; |
| 94 | let response = null; |
| 95 | |
| 96 | const abort = () => { |
| 97 | const error = new AbortError("The operation was aborted."); |
| 98 | reject(error); |
| 99 | if (request.body && request.body instanceof Stream.Readable) { |
| 100 | request.body.destroy(error); |
| 101 | } |
| 102 | |
| 103 | if (!response || !response.body) { |
| 104 | return; |
| 105 | } |
| 106 | |
| 107 | response.body.emit("error", error); |
| 108 | }; |
| 109 | |
| 110 | if (signal && signal.aborted) { |
| 111 | abort(); |
| 112 | return; |
| 113 | } |
| 114 | |
| 115 | const abortAndFinalize = () => { |
| 116 | abort(); |
| 117 | finalize(); |
| 118 | }; |
| 119 | |
| 120 | // Send request |
| 121 | const request_ = send(parsedURL.toString(), options); |
| 122 | |
| 123 | if (signal) { |
| 124 | signal.addEventListener("abort", abortAndFinalize); |
| 125 | } |
| 126 | |
| 127 | const finalize = () => { |
| 128 | request_.abort(); |
no test coverage detected