Files
webrequest/ts/utils/timeout.ts

59 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

/**
* Timeout handling utilities
*/
import * as plugins from '../webrequest.plugins.js';
/**
* Create an AbortController with timeout
*/
export function createTimeoutController(timeoutMs: number): {
controller: AbortController;
cleanup: () => void;
} {
const controller = new AbortController();
// Use Timeout directly so we can cancel it when the fetch completes
const timeout = new plugins.smartdelay.Timeout(timeoutMs, null);
timeout.promise.then(() => {
controller.abort();
});
// Cleanup function to cancel the timeout timer
const cleanup = () => {
timeout.cancel();
};
return { controller, cleanup };
}
/**
* Execute a fetch with timeout
*/
export async function fetchWithTimeout(
url: string,
init: RequestInit,
timeoutMs: number,
): Promise<Response> {
const { controller, cleanup } = createTimeoutController(timeoutMs);
try {
const response = await fetch(url, {
...init,
signal: controller.signal,
});
cleanup();
return response;
} catch (error) {
cleanup();
// Re-throw with more informative error if it's a timeout
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`Request timeout after ${timeoutMs}ms: ${url}`);
}
throw error;
}
}