@rtorcato/js-common / fetch
fetch
Functions
fetchWithTimeout()
fetchWithTimeout(
url,options?,timeout?):Promise<unknown>
Defined in: fetch/index.ts:16
Fetches a resource with a timeout.
Example
await fetchWithTimeout('https://api.example.com/health') // { status: 'ok' }
await fetchWithTimeout('https://slow.example.com', {}, 500)
// rejects with AbortError after 500ms
Parameters
url
string
The URL to fetch.
options?
RequestInit = {}
Fetch options.
timeout?
number = 8000
Timeout in milliseconds (default: 8000).
Returns
Promise<unknown>
The parsed JSON response.
postJson()
postJson<
T,R>(url,body,options?):Promise<R>
Defined in: fetch/index.ts:49
Sends a POST request with a JSON body.
Example
const user = await postJson<{ name: string }, { id: number }>(
'https://api.example.com/users',
{ name: 'Ada' }
)
user.id // 42
Type Parameters
T
T = unknown
R
R = unknown
Parameters
url
string
The URL to post to.
body
T
The body to send.
options?
RequestInit = {}
Additional fetch options.
Returns
Promise<R>
The parsed JSON response.
getJson()
getJson<
T>(url,options?):Promise<T>
Defined in: fetch/index.ts:76
Sends a GET request and returns JSON.
Example
const user = await getJson<{ id: number }>('https://api.example.com/users/42')
user.id // 42
Type Parameters
T
T = unknown
Parameters
url
string
The URL to fetch.
options?
RequestInit = {}
Additional fetch options.
Returns
Promise<T>
The parsed JSON response.
fetchText()
fetchText(
url,options?):Promise<string>
Defined in: fetch/index.ts:87
Fetches a resource and returns the response as text.
Parameters
url
string
The URL to fetch.
options?
RequestInit = {}
Fetch options.
Returns
Promise<string>
The response as text.
handleApiError()
handleApiError<
T>(promise,fallback?):Promise<T>
Defined in: fetch/index.ts:98
Handles fetch errors and returns a fallback value or throws.
Type Parameters
T
T
Parameters
promise
Promise<T>
The fetch promise.
fallback?
T
The fallback value to return on error.
Returns
Promise<T>
The resolved value or the fallback.