freshyo/apps/user-ui/src/lib/fetch-json.ts
2026-10-10 19:56:02 +05:30

37 lines
1.3 KiB
TypeScript

import axios from 'axios'
/**
* Hard cap for catalogue / CDN JSON requests.
*
* `handleRefresh` on the home screen waits for the products/stores/slots/consts refetches and only then
* clears its pull-to-refresh indicator. Those fetches had no timeout, so a single stalled connection left
* the spinner turning until the app was relaunched. Failing (with an abort) is far better than hanging.
*/
export const JSON_FETCH_TIMEOUT_MS = 90_000
/** True for the errors an aborted/cancelled request produces (axios or fetch). */
export function isAbortError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const candidate = error as { name?: string; code?: string }
return (
candidate.name === 'CanceledError' ||
candidate.name === 'AbortError' ||
candidate.code === 'ERR_CANCELED'
)
}
/**
* GET a JSON document with a bounded lifetime. The timeout is per request and the controller is always
* disposed, so nothing leaks when the request settles early.
*/
export async function fetchJson<T>(url: string, timeoutMs: number = JSON_FETCH_TIMEOUT_MS): Promise<T> {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs)
try {
const response = await axios.get<T>(url, { signal: controller.signal })
return response.data
} finally {
clearTimeout(timer)
}
}