(
url: string,
options: RequestInit,
timeoutMs: number,
externalSignal?: AbortSignal,
)
| 116 | // Fetch with timeout using AbortController |
| 117 | // Supports both internal timeout and external signal for cancellation |
| 118 | async function fetchWithTimeout( |
| 119 | url: string, |
| 120 | options: RequestInit, |
| 121 | timeoutMs: number, |
| 122 | externalSignal?: AbortSignal, |
| 123 | ): Promise<Response> { |
| 124 | const controller = new AbortController(); |
| 125 | const timeoutId = setTimeout(() => controller.abort(), timeoutMs); |
| 126 | |
| 127 | // If an external signal is provided, abort our controller when it aborts |
| 128 | const abortHandler = externalSignal ? () => controller.abort() : undefined; |
| 129 | if (externalSignal && abortHandler) { |
| 130 | externalSignal.addEventListener("abort", abortHandler); |
| 131 | } |
| 132 | |
| 133 | try { |
| 134 | const response = await fetch(url, { |
| 135 | ...options, |
| 136 | signal: controller.signal, |
| 137 | }); |
| 138 | return response; |
| 139 | } catch (err) { |
| 140 | // Check if it was cancelled by external signal |
| 141 | if (externalSignal?.aborted) { |
| 142 | throw new PollinationsError( |
| 143 | "Request was cancelled", |
| 144 | "CANCELLED", |
| 145 | 499, // Client Closed Request |
| 146 | ); |
| 147 | } |
| 148 | if ((err as Error).name === "AbortError") { |
| 149 | throw new PollinationsError( |
| 150 | `Request timed out after ${timeoutMs}ms`, |
| 151 | "TIMEOUT", |
| 152 | 408, |
| 153 | ); |
| 154 | } |
| 155 | throw err; |
| 156 | } finally { |
| 157 | clearTimeout(timeoutId); |
| 158 | if (externalSignal && abortHandler) { |
| 159 | externalSignal.removeEventListener("abort", abortHandler); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | // Strip API key from URL for safe sharing |
| 165 | function stripKeyFromUrl(url: string): string { |
no test coverage detected