(progress: Progress | undefined, params: HTTPRequestParams, onError?: (params: HTTPRequestParams, response: http.IncomingMessage) => Promise<Error>)
| 22 | import type { Progress } from './progress'; |
| 23 | |
| 24 | export async function fetchData(progress: Progress | undefined, params: HTTPRequestParams, onError?: (params: HTTPRequestParams, response: http.IncomingMessage) => Promise<Error>): Promise<string> { |
| 25 | const promise = new ManualPromise<string>(); |
| 26 | const { cancel } = httpRequest(params, async response => { |
| 27 | if (response.statusCode !== 200) { |
| 28 | const error = onError ? await onError(params, response) : new Error(`fetch failed: server returned code ${response.statusCode}. URL: ${params.url}`); |
| 29 | promise.reject(error); |
| 30 | return; |
| 31 | } |
| 32 | let body = ''; |
| 33 | response.on('data', (chunk: string) => body += chunk); |
| 34 | response.on('error', (error: any) => promise.reject(error)); |
| 35 | response.on('end', () => promise.resolve(body)); |
| 36 | }, error => promise.reject(error)); |
| 37 | if (!progress) |
| 38 | return promise; |
| 39 | try { |
| 40 | return await progress.race(promise); |
| 41 | } catch (error) { |
| 42 | cancel(error); |
| 43 | throw error; |
| 44 | } |
| 45 | } |
no test coverage detected
searching dependent graphs…