@tripathirajan/fetcher - v1.0.2
    Preparing search index...

    Class Fetcher

    Fetcher is a universal HTTP client that supports fetch and XHR fallback. It provides methods for making requests, handling responses, and managing interceptors. It supports automatic retries, timeouts, and progress reporting for downloads and uploads.

    const fetcher = new Fetcher({
    baseURL: "https://api.example.com",
    headers: {
    "Authorization": "Bearer token",
    "Content-Type": "application/json"
    },
    timeout: 5000, // 5 seconds
    retries: 3 // Retry failed requests up to 3 times
    });
    Index

    Constructors

    Properties

    baseURL: string

    The base URL for all requests. This is prepended to the request path when making requests.

    credentials?: RequestCredentials

    Credentials mode for requests.

    • 'same-origin': Send cookies for same-origin requests.
    • 'include': Always send cookies, even for cross-origin requests.
    • 'omit': Never send cookies.
    defaultHeaders: Record<string, string>

    Default headers to include in every request. These headers will be merged with any headers provided in individual requests.

    interceptors: Interceptors = ...

    Interceptors for modifying requests and responses. This object provides methods to register request and response interceptors.

    retries: number = 0

    Number of times to retry failed requests. If a request fails, it will be retried this many times before throwing an error.

    timeout: number = 6000

    Default timeout for requests in milliseconds. If a request takes longer than this time, it will be aborted.

    Methods

    • Performs a DELETE request.

      Parameters

      • url: string

        The request path.

      • config: RequestConfig = {}

        Optional request configuration.

      Returns Promise<Response>

      A Promise resolving to the Response.

      fetcher.delete('/users/1')
      .then(response => console.log('Deleted successfully'))
      .catch(err => console.error(err));
    • Downloads a file while reporting progress.

      Parameters

      • url: string

        The request path.

      • onProgress: (loaded: number, total: null | number) => void

        Callback for download progress.

      • config: RequestConfig = {}

        Optional request configuration.

      Returns Promise<Blob>

      A Promise resolving to the downloaded Blob.

      If used in a non-browser environment.

      browser

      This method is only supported in browser environments.

      fetcher.downloadWithProgress('/file.zip', (loaded, total) => {
      const percentComplete = total ? (loaded / total) * 100 : 0;
      console.log(`Download progress: ${percentComplete}%`);
      })
      .then(blob => {
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'file.zip';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      })
      .catch(err => console.error(err));
    • Performs a GET request and parses JSON.

      Parameters

      • url: string

        The request path.

      • config: RequestConfig = {}

        Optional request configuration.

      Returns Promise<Response>

      A Promise resolving to the Response.

      fetcher.get('/users')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));

    post

    • post(url: string, body: unknown, config?: RequestConfig): Promise<Response>

      Performs a POST request with a JSON body.

      Parameters

      • url: string

        The request path.

      • body: unknown

        The JSON payload.

      • config: RequestConfig = {}

        Optional request configuration.

      Returns Promise<Response>

      A Promise resolving to the Response.

      fetcher.post('/users', { name: 'John Doe' })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
    • Performs a POST request with upload progress reporting using XHR.

      Parameters

      • url: string

        The request path.

      • body: string | Blob | FormData

        The payload to upload.

      • onUploadProgress: (event: ProgressEvent) => void

        Callback for upload progress.

      • config: RequestConfig = {}

        Optional request configuration.

      Returns Promise<Response>

      A Promise resolving to the Response.

      If used in a non-browser environment.

      This method is only supported in browser environments.

      browser

      fetcher.postWithUploadProgress('/upload', formData, (event) => {
      const percentComplete = (event.loaded / event.total) * 100;
      console.log(`Upload progress: ${percentComplete}%`);
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
    • Performs a PUT request with a JSON body.

      Parameters

      • url: string

        The request path.

      • body: unknown

        The JSON payload.

      • config: RequestConfig = {}

        Optional request configuration.

      Returns Promise<Response>

      A Promise resolving to the response.

    • Performs a raw HTTP request.

      Parameters

      • url: string

        The request path relative to baseURL.

      • config: RequestConfig = {}

        Request configuration.

      Returns Promise<Response>

      A Promise resolving to the Response object.

      fetcher.request('/users', {
      method: 'GET',
      headers: {
      'Authorization': 'Bearer token'
      },
      timeout: 5000, // Override default timeout
      retries: 3, // Retry failed requests up to 3 times
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
      fetcher.request('/users', {
      method: 'POST',
      body: JSON.stringify({ name: 'John Doe' }),
      headers: { 'Content-Type': 'application/json' },
      })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));