Skip to content

Commit

Permalink
fix: add timeout to cache calls (#163)
Browse files Browse the repository at this point in the history
  • Loading branch information
jstashh authored Nov 16, 2021
1 parent e889748 commit 9fd3984
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,14 @@ export class CachedFetcher<T> {
path += `?${queryParameters}`;
}

const call = await fetch(path);
let call: Response;
try {
const timeout = 5000;
call = await this.fetchWithTimeout(path, timeout);
} catch {
console.warn(`Call to cache at ${path} timed out`);
return undefined;
}
if (call.status !== 200) {
const { url, status, statusText } = call;
console.warn(`Call to cache failed at ${url} (status ${status} ${statusText})`);
Expand All @@ -50,6 +57,13 @@ export class CachedFetcher<T> {
return json as T;
}

private async fetchWithTimeout(url: string, timeout: number): Promise<Response> {
return Promise.race([
fetch(url),
new Promise<Response>((_, reject) => setTimeout(() => reject("timeout"), timeout))
]);
}

private get currentValue(): T | undefined {
if (!this.expiryDate) {
return undefined;
Expand Down

0 comments on commit 9fd3984

Please sign in to comment.