Webformula core
Welcome Getting started Routing Serve / Build Binding variables Web component Fetcher Multiple languages github-circle-black-transparent GitHub github-circle-black-transparent Example app

Fetcher

Extension on fetch that includes interceptors
Fetcher
            
      import { fetcher, createFetcher } from '@webformula/core';

  /** Main fetcher */
  
  // interceptors
  fetcher('/get', { interceptors: {
    // called on 401
    auth(config) {
      config.headers.Authorization = 'Bearer token';
      return config;
    },
    before(config) {
      // modify config
      return config;
    }
  });

  /** Example: JWT refresh access token on 401 */
  fetcher('/get', { interceptors: {
    async auth(config) {
      const refreshResponse = await fetcher('/refreshToken', {
        headers: { Authorization: 'Bearer refresh_token' }
      });
      config.headers.Authorization = await refreshResponse.text();
      return config;
    }
  });


  /** Fetcher instance */
  
  // global config for all instance requests
  const fetcherInstance = createFetcher({
    baseUrl: '',
    headers: {
      Authorization: 'Bearer token'
    },
    interceptors: {
      auth(config) {
        config.headers.Authorization = 'Bearer token';
        return config;
      },
      before(config) {
        // modify config
        return config;
      }
    }
  });
  
  fetcherInstance('/get');
  
  // request specific interceptors using an instance
  fetcherInstance('/get', {}, interceptors: {
    auth(config) {
      config.headers.Authorization = 'Bearer token';
      return config;
    },
    before(config) {
      config.headers.Authorization = 'Bearer token';
      return config;
    }
  });