Skip to main content

@rtorcato/js-common / fetch

fetch

Functions​

fetchWithTimeout()​

fetchWithTimeout(url, options?, timeout?): Promise<unknown>

Defined in: fetch/index.ts:19

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 a TimeoutError DOMException after 500ms (covers the body read too)
const controller = new AbortController()
await fetchWithTimeout('https://api.example.com', { signal: controller.signal })
// controller.abort() rejects with AbortError

Parameters​

url​

string

The URL to fetch.

options?​

RequestInit = {}

Fetch options. A caller signal is honoured alongside the timeout.

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:47

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:74

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:85

Fetches a resource and returns the response as text.

Parameters​

url​

string

The URL to fetch.

options?​

RequestInit = {}

Fetch options. A caller signal is honoured alongside the timeout.

Returns​

Promise<string>

The response as text.


handleApiError()​

handleApiError<T>(promise, fallback?): Promise<T>

Defined in: fetch/index.ts:96

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.