|
| 1 | +import { ApiErrorResponse } from './models'; |
| 2 | + |
| 3 | +export interface StringKeyWithStringValue { |
| 4 | + [key: string]: string; |
| 5 | +} |
| 6 | + |
| 7 | +export interface HttpOptions { |
| 8 | + uri: string; |
| 9 | + body?: any; |
| 10 | + encoding?: BufferEncoding | null; |
| 11 | + form?: StringKeyWithStringValue; |
| 12 | + headers?: StringKeyWithStringValue; |
| 13 | + json?: boolean; |
| 14 | + method?: string; |
| 15 | + qs?: StringKeyWithStringValue; |
| 16 | +} |
| 17 | + |
| 18 | +export interface HttpResponse { |
| 19 | + statusCode: number; |
| 20 | + statusMessage: string; |
| 21 | + headers: NodeJS.Dict<string | string[]>; |
| 22 | + body: any; |
| 23 | +} |
| 24 | + |
| 25 | +export interface HttpResult { |
| 26 | + response: HttpResponse; |
| 27 | + body: any; |
| 28 | +} |
| 29 | + |
| 30 | +export interface HttpRejectType { |
| 31 | + response: HttpResponse | null; |
| 32 | + errorResponse: ApiErrorResponse | null; |
| 33 | + error: Error; |
| 34 | +} |
| 35 | + |
| 36 | +interface FetchHeaders { |
| 37 | + forEach(callback: (value: string, key: string) => void): void; |
| 38 | +} |
| 39 | + |
| 40 | +interface FetchResponse { |
| 41 | + status: number; |
| 42 | + statusText: string; |
| 43 | + headers: FetchHeaders; |
| 44 | + ok: boolean; |
| 45 | + arrayBuffer(): Promise<ArrayBuffer>; |
| 46 | +} |
| 47 | + |
| 48 | +interface FetchRequestInit { |
| 49 | + method?: string; |
| 50 | + headers?: StringKeyWithStringValue; |
| 51 | + body?: any; |
| 52 | +} |
| 53 | + |
| 54 | +type Fetcher = (input: string | URL, init?: FetchRequestInit) => Promise<FetchResponse>; |
| 55 | + |
| 56 | +export class HttpClient { |
| 57 | + public requestAsync(options: HttpOptions): Promise<HttpResult> { |
| 58 | + const url: URL = options.qs |
| 59 | + ? new URL(`?${new URLSearchParams(options.qs).toString()}`, options.uri) |
| 60 | + : new URL(options.uri); |
| 61 | + |
| 62 | + const requestBody = this.buildRequestBody(options); |
| 63 | + |
| 64 | + const responseEncoding: BufferEncoding | null = options.encoding === null ? null : options.encoding || 'utf-8'; |
| 65 | + |
| 66 | + const requestOptions: FetchRequestInit = { |
| 67 | + method: options.method || 'GET', |
| 68 | + headers: options.headers, |
| 69 | + }; |
| 70 | + |
| 71 | + if (requestBody) { |
| 72 | + requestOptions.body = requestBody; |
| 73 | + } |
| 74 | + |
| 75 | + return this.doFetchRequest(url, requestOptions, responseEncoding); |
| 76 | + } |
| 77 | + |
| 78 | + private buildRequestBody(options: HttpOptions) { |
| 79 | + let requestBody = options.body; |
| 80 | + if (options.form) { |
| 81 | + // Override requestBody for form with form content |
| 82 | + requestBody = new URLSearchParams(options.form).toString(); |
| 83 | + options.headers = Object.assign( |
| 84 | + { |
| 85 | + 'Content-Type': 'application/x-www-form-urlencoded', |
| 86 | + }, |
| 87 | + options.headers |
| 88 | + ); |
| 89 | + } |
| 90 | + if (options.json) { |
| 91 | + // Override requestBody with JSON value |
| 92 | + requestBody = JSON.stringify(options.body); |
| 93 | + options.headers = Object.assign( |
| 94 | + { |
| 95 | + 'Content-Type': 'application/json', |
| 96 | + }, |
| 97 | + options.headers |
| 98 | + ); |
| 99 | + } |
| 100 | + return requestBody; |
| 101 | + } |
| 102 | + |
| 103 | + private async doFetchRequest( |
| 104 | + url: URL, |
| 105 | + requestOptions: FetchRequestInit, |
| 106 | + responseEncoding: BufferEncoding | null |
| 107 | + ): Promise<HttpResult> { |
| 108 | + const fetcher = this.getFetch(); |
| 109 | + let response: FetchResponse; |
| 110 | + try { |
| 111 | + response = await fetcher(url.toString(), requestOptions); |
| 112 | + } catch (error) { |
| 113 | + return Promise.reject({ |
| 114 | + response: null, |
| 115 | + error: this.normalizeFetchError(error), |
| 116 | + errorResponse: null, |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + const respBody = await this.readResponseBody(response, responseEncoding); |
| 121 | + const responseHeaders = this.toHeaderDict(response.headers); |
| 122 | + |
| 123 | + const httpResponse: HttpResponse = { |
| 124 | + statusCode: response.status, |
| 125 | + statusMessage: response.statusText, |
| 126 | + headers: responseHeaders, |
| 127 | + body: respBody, |
| 128 | + }; |
| 129 | + |
| 130 | + if (response.ok) { |
| 131 | + return { |
| 132 | + response: httpResponse, |
| 133 | + body: respBody, |
| 134 | + }; |
| 135 | + } |
| 136 | + |
| 137 | + const rejectObject: HttpRejectType = { |
| 138 | + response: httpResponse, |
| 139 | + error: new Error(`Error on '${url}': ${response.status} ${response.statusText}`), |
| 140 | + errorResponse: null, |
| 141 | + }; |
| 142 | + let errorResponse = null; |
| 143 | + try { |
| 144 | + errorResponse = JSON.parse(respBody.toString()) as ApiErrorResponse; |
| 145 | + } catch (parseError) {} |
| 146 | + |
| 147 | + if (errorResponse) { |
| 148 | + rejectObject.errorResponse = errorResponse; |
| 149 | + } else { |
| 150 | + rejectObject.error.message += `. ${respBody}`; |
| 151 | + } |
| 152 | + |
| 153 | + return Promise.reject(rejectObject); |
| 154 | + } |
| 155 | + |
| 156 | + private async readResponseBody( |
| 157 | + response: FetchResponse, |
| 158 | + responseEncoding: BufferEncoding | null |
| 159 | + ): Promise<string | Buffer> { |
| 160 | + const arrayBuffer = await response.arrayBuffer(); |
| 161 | + const buffer = Buffer.from(arrayBuffer); |
| 162 | +
|
| 163 | + if (responseEncoding === null) { |
| 164 | + return buffer; |
| 165 | + } |
| 166 | + |
| 167 | + return buffer.toString(responseEncoding); |
| 168 | + } |
| 169 | + |
| 170 | + private toHeaderDict(headers: FetchHeaders): NodeJS.Dict<string | string[]> { |
| 171 | + const normalizedHeaders: NodeJS.Dict<string | string[]> = {}; |
| 172 | + |
| 173 | + headers.forEach((value, key) => { |
| 174 | + const existing = normalizedHeaders[key]; |
| 175 | + if (existing === undefined) { |
| 176 | + normalizedHeaders[key] = value; |
| 177 | + return; |
| 178 | + } |
| 179 | + |
| 180 | + if (Array.isArray(existing)) { |
| 181 | + existing.push(value); |
| 182 | + normalizedHeaders[key] = existing; |
| 183 | + return; |
| 184 | + } |
| 185 | + |
| 186 | + normalizedHeaders[key] = [existing, value]; |
| 187 | + }); |
| 188 | + |
| 189 | + return normalizedHeaders; |
| 190 | + } |
| 191 | + |
| 192 | + private getFetch(): Fetcher { |
| 193 | + const fetcher = (globalThis as { fetch?: Fetcher }).fetch; |
| 194 | + if (!fetcher) { |
| 195 | + throw new Error('Global fetch API is not available. Please use Node.js 18+.'); |
| 196 | + } |
| 197 | + |
| 198 | + return fetcher; |
| 199 | + } |
| 200 | + |
| 201 | + private normalizeFetchError(error: unknown): Error { |
| 202 | + if (error instanceof Error) { |
| 203 | + const mutableError = error as Error & { code?: string; cause?: unknown; name: string }; |
| 204 | + let normalizedCode = mutableError.code; |
| 205 | + |
| 206 | + if (!normalizedCode) { |
| 207 | + const cause = mutableError.cause; |
| 208 | + if (cause && typeof cause === 'object' && 'code' in (cause as { code?: string })) { |
| 209 | + const code = (cause as { code?: string }).code; |
| 210 | + if (code) { |
| 211 | + normalizedCode = String(code); |
| 212 | + } |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | + if (!normalizedCode) { |
| 217 | + normalizedCode = mutableError.name || 'FETCH_ERROR'; |
| 218 | + } |
| 219 | + |
| 220 | + try { |
| 221 | + if (!mutableError.code) { |
| 222 | + mutableError.code = normalizedCode; |
| 223 | + } |
| 224 | + } catch (assignError) {} |
| 225 | + |
| 226 | + if (mutableError.code) { |
| 227 | + return mutableError; |
| 228 | + } |
| 229 | + |
| 230 | + const wrapped = new Error(mutableError.message); |
| 231 | + wrapped.name = mutableError.name; |
| 232 | + (wrapped as { code?: string }).code = normalizedCode; |
| 233 | + return wrapped; |
| 234 | + } |
| 235 | + |
| 236 | + const wrapped = new Error(String(error)); |
| 237 | + (wrapped as { code?: string }).code = 'FETCH_ERROR'; |
| 238 | + return wrapped; |
| 239 | + } |
| 240 | +} |
0 commit comments