@alwatr/fetch
Version:
`@alwatr/fetch` is an enhanced, lightweight, and dependency-free wrapper for the native `fetch` API. It provides modern features like caching strategies, request retries, timeouts, and intelligent duplicate request handling, all in a compact package.
99 lines • 3.64 kB
TypeScript
/**
* @module @alwatr/fetch
*
* An enhanced, lightweight, and dependency-free wrapper for the native `fetch`
* API. It provides modern features like caching strategies, request retries,
* timeouts, and duplicate request handling.
*/
import { cacheSupported } from './core.js';
import { FetchError } from './error.js';
import type { FetchJsonOptions, FetchOptions, FetchResponse } from './type.js';
export { cacheSupported };
export * from './error.js';
export type * from './type.js';
/**
* An enhanced wrapper for the native `fetch` function.
*
* This function extends the standard `fetch` with additional features such as:
* - **Timeout**: Aborts the request if it takes too long.
* - **Retry Pattern**: Automatically retries the request on failure (e.g., server errors or network issues).
* - **Duplicate Request Handling**: Prevents sending multiple identical requests in parallel.
* - **Cache Strategies**: Provides various caching mechanisms using the browser's Cache API.
* - **Simplified API**: Offers convenient options for adding query parameters, JSON bodies, and auth tokens.
*
* @see {@link FetchOptions} for a detailed list of available options.
*
* @param {string} url - The URL to fetch.
* @param {FetchOptions} options - Optional configuration for the fetch request.
* @returns {Promise<FetchResponse>} A promise that resolves to a tuple. On
* success, it returns `[response, null]`. On failure, it returns `[null,
* FetchError]`.
*
* @example
* ```typescript
* import {fetch} from '@alwatr/fetch';
*
* async function fetchProducts() {
* const [response, error] = await fetch('/api/products', {
* queryParams: { limit: 10 },
* timeout: 5_000,
* });
*
* if (error) {
* console.error('Request failed:', error.reason);
* return;
* }
*
* // At this point, response is guaranteed to be valid and ok.
* const data = await response.json();
* console.log('Products:', data);
* }
*
* fetchProducts();
* ```
*/
export declare function fetch(url: string, options?: FetchOptions): Promise<FetchResponse>;
/**
* An enhanced wrapper for the native `fetch` function that automatically parses JSON responses.
*
* This function extends the standard `fetch` with the same features (timeout, retry, caching, etc.)
* and automatically parses the response body as JSON. It returns a tuple with the parsed data or an error.
*
* @template T - The expected type of the JSON response data.
*
* @param {string} url - The URL to fetch.
* @param {FetchOptions} options - Optional configuration for the fetch request.
* @returns {Promise<[T, null] | [null, FetchError]>} A promise that resolves to a tuple.
* On success, it returns `[data, null]` where data is the parsed JSON.
* On failure, it returns `[null, FetchError]`.
*
* @example
* ```typescript
* import {fetchJson} from '@alwatr/fetch';
*
* interface Product {
* ok: true;
* id: number;
* name: string;
* price: number;
* }
*
* async function getProduct(id: number) {
* const [data, error] = await fetchJson<Product>(`/api/products/${id}`, {
* timeout: 5_000,
* cacheStrategy: 'cache_first',
* requireResponseJsonWithOkTrue: true,
* });
*
* if (error) {
* console.error('Failed to fetch product:', error.reason);
* return;
* }
*
* // data is now typed as Product and guaranteed to be valid
* console.log('Product name:', data.name);
* }
* ```
*/
export declare function fetchJson<T extends JsonObject = JsonObject>(url: string, options?: FetchJsonOptions): Promise<[T, null] | [null, FetchError]>;
//# sourceMappingURL=main.d.ts.map