@happy-ts/fetch-t
    Preparing search index...

    Function fetchT

    Enhanced fetch function that wraps the native Fetch API with additional capabilities.

    Features:

    • Abortable requests: Set abortable: true to get a FetchTask with abort() method.
    • Type-safe responses: Use responseType to automatically parse responses as text, JSON, ArrayBuffer, Blob, bytes, or stream.
    • Timeout support: Set timeout in milliseconds to auto-abort long-running requests.
    • Progress tracking: Use onProgress callback to track download progress (requires Content-Length header).
    • Chunk streaming: Use onChunk callback to receive raw data chunks as they arrive.
    • Retry support: Use retry to automatically retry failed requests with configurable delay and conditions.
    • Result type error handling: Returns Result<T, Error> instead of throwing exceptions for runtime errors.

    Note: Invalid parameters throw synchronously (fail-fast) rather than returning rejected Promises. This differs from native fetch behavior and helps catch programming errors during development.

    The expected type of the response data.

    The resource to fetch. Can be a URL object or a string representing a URL.

    Additional options for the fetch operation, extending standard RequestInit with custom properties.

    A FetchTask<T> if abortable: true, otherwise a FetchResult<T> (which is AsyncIOResult<T>).

    If url is invalid or a relative URL in non-browser environment.

    If responseType is not a valid response type.

    If timeout is not a number.

    If timeout is not greater than 0.

    If onProgress or onChunk is provided but not a function.

    If retry.retries is not an integer.

    If retry.retries is negative.

    If retry.delay is not a number or function.

    If retry.delay is a negative number.

    If retry.when is not an array or function.

    If retry.onRetry is provided but not a function.

    // Basic GET request - returns Response object wrapped in Result
    const result = await fetchT('https://api.example.com/data');
    result
    .inspect((res) => console.log('Status:', res.status))
    .inspectErr((err) => console.error('Error:', err));
    // GET JSON with type safety
    interface User {
    id: number;
    name: string;
    }
    const result = await fetchT<User>('https://api.example.com/user/1', {
    responseType: 'json',
    });
    result.inspect((user) => console.log(user.name));
    // POST request with JSON body
    const result = await fetchT<User>('https://api.example.com/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'John' }),
    responseType: 'json',
    });
    // Abortable request with timeout
    const task = fetchT('https://api.example.com/data', {
    abortable: true,
    timeout: 5000, // 5 seconds
    });

    // Cancel the request if needed
    task.abort('User cancelled');

    // Check if aborted
    console.log('Aborted:', task.aborted);

    // Wait for result
    const result = await task.result;
    // Track download progress
    const result = await fetchT('https://example.com/large-file.zip', {
    responseType: 'blob',
    onProgress: (progressResult) => {
    progressResult
    .inspect(({ completedByteLength, totalByteLength }) => {
    const percent = ((completedByteLength / totalByteLength) * 100).toFixed(1);
    console.log(`Progress: ${percent}%`);
    })
    .inspectErr((err) => console.warn('Progress unavailable:', err.message));
    },
    });
    // Stream data chunks
    const chunks: Uint8Array[] = [];
    const result = await fetchT('https://example.com/stream', {
    onChunk: (chunk) => chunks.push(chunk),
    });
    // Retry with exponential backoff
    const result = await fetchT('https://api.example.com/data', {
    retry: {
    retries: 3,
    delay: (attempt) => Math.min(1000 * Math.pow(2, attempt - 1), 10000),
    when: [500, 502, 503, 504],
    onRetry: (error, attempt) => console.log(`Retry ${attempt}: ${error.message}`),
    },
    responseType: 'json',
    });
    • Fetches a resource from the network as a text string and returns an abortable FetchTask.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true; responseType: "text" }

        Additional options for the fetch operation, must include abortable: true and responseType: 'text'.

      Returns FetchTask<string>

      A FetchTask representing the abortable operation with a string response.

    • Fetches a resource from the network as an ArrayBuffer and returns an abortable FetchTask.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true; responseType: "arraybuffer" }

        Additional options for the fetch operation, must include abortable: true and responseType: 'arraybuffer'.

      Returns FetchTask<ArrayBuffer>

      A FetchTask representing the abortable operation with an ArrayBuffer response.

    • Fetches a resource from the network as a Blob and returns an abortable FetchTask.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true; responseType: "blob" }

        Additional options for the fetch operation, must include abortable: true and responseType: 'blob'.

      Returns FetchTask<Blob>

      A FetchTask representing the abortable operation with a Blob response.

    • Fetches a resource from the network and parses it as JSON, returning an abortable FetchTask.

      Type Parameters

      • T

        The expected type of the parsed JSON data.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true; responseType: "json" }

        Additional options for the fetch operation, must include abortable: true and responseType: 'json'.

      Returns FetchTask<T | null>

      A FetchTask representing the abortable operation with a response parsed as type T.

    • Fetches a resource from the network as a ReadableStream and returns an abortable FetchTask.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true; responseType: "stream" }

        Additional options for the fetch operation, must include abortable: true and responseType: 'stream'.

      Returns FetchTask<ReadableStream<Uint8Array<ArrayBuffer>> | null>

      A FetchTask representing the abortable operation with a ReadableStream<Uint8Array<ArrayBuffer>> response.

    • Fetches a resource from the network as a Uint8Array and returns an abortable FetchTask.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true; responseType: "bytes" }

        Additional options for the fetch operation, must include abortable: true and responseType: 'bytes'.

      Returns FetchTask<Uint8Array<ArrayBuffer>>

      A FetchTask representing the abortable operation with a Uint8Array<ArrayBuffer> response.

    • Fetches a resource from the network and returns an abortable FetchTask with a dynamic response type.

      Use this overload when responseType is a FetchResponseType union type.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true; responseType: FetchResponseType }

        Additional options for the fetch operation, must include abortable: true and a FetchResponseType.

      Returns FetchTask<FetchResponseData>

      A FetchTask representing the abortable operation with a FetchResponseData response.

    • Fetches a resource from the network as a text string.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable?: false; responseType: "text" }

        Additional options for the fetch operation, must include responseType: 'text' and abortable must be false or omitted.

      Returns FetchResult<string>

      A FetchResult representing the operation with a string response.

    • Fetches a resource from the network as an ArrayBuffer.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable?: false; responseType: "arraybuffer" }

        Additional options for the fetch operation, must include responseType: 'arraybuffer' and abortable must be false or omitted.

      Returns FetchResult<ArrayBuffer>

      A FetchResult representing the operation with an ArrayBuffer response.

    • Fetches a resource from the network as a Blob.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable?: false; responseType: "blob" }

        Additional options for the fetch operation, must include responseType: 'blob' and abortable must be false or omitted.

      Returns FetchResult<Blob>

      A FetchResult representing the operation with a Blob response.

    • Fetches a resource from the network and parses it as JSON.

      Type Parameters

      • T

        The expected type of the parsed JSON data.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable?: false; responseType: "json" }

        Additional options for the fetch operation, must include responseType: 'json' and abortable must be false or omitted.

      Returns FetchResult<T | null>

      A FetchResult representing the operation with a response parsed as type T.

    • Fetches a resource from the network as a ReadableStream.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable?: false; responseType: "stream" }

        Additional options for the fetch operation, must include responseType: 'stream' and abortable must be false or omitted.

      Returns FetchResult<ReadableStream<Uint8Array<ArrayBuffer>> | null>

      A FetchResult representing the operation with a ReadableStream<Uint8Array<ArrayBuffer>> response.

    • Fetches a resource from the network as a Uint8Array.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable?: false; responseType: "bytes" }

        Additional options for the fetch operation, must include responseType: 'bytes' and abortable must be false or omitted.

      Returns FetchResult<Uint8Array<ArrayBuffer>>

      A FetchResult representing the operation with a Uint8Array<ArrayBuffer> response.

    • Fetches a resource from the network with a dynamic response type (non-abortable).

      Use this overload when responseType is a FetchResponseType union type.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable?: false; responseType: FetchResponseType }

        Additional options for the fetch operation with a FetchResponseType, and abortable must be false or omitted.

      Returns FetchResult<FetchResponseData>

      A FetchResult representing the operation with a FetchResponseData response.

    • Fetches a resource from the network and returns an abortable FetchTask with a generic Response.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • init: FetchInit & { abortable: true }

        Additional options for the fetch operation, must include abortable: true.

      Returns FetchTask<Response>

      A FetchTask representing the abortable operation with a Response object.

    • Fetches a resource from the network and returns a FetchResult with a generic Response object.

      Parameters

      • url: string | URL

        The resource to fetch. Can be a URL object or a string representing a URL.

      • Optionalinit: FetchInit & { abortable?: false }

        Optional additional options for the fetch operation, and abortable must be false or omitted.

      Returns FetchResult<Response>

      A FetchResult representing the operation with a Response object.