ChemPal Documentation - v1.6.0
    Preparing search index...

    Function fetchDecorator

    • A lightweight fetch wrapper that automatically parses response bodies based on their Content-Type header and attaches a deterministic request hash to each response. Supports JSON, text, and binary (blob) content types.

      Parameters

      • url: string

        The URL to fetch

      • options: RequestInit = {}

        Standard RequestInit options forwarded to fetch()

      Returns Promise<Response & { data: unknown; requestHash: string }>

      An object spreading the original response with data (parsed body) and requestHash (hex hash of the request parameters)

      This is the utility-layer fetch decorator used in src/utils/. For the primary application fetch decorator with LRU caching, response aggregation, and richer error handling, see the fetchDecorator in src/helpers/fetch.ts.

      If the response status is not OK (non-2xx)

      const result = await fetchDecorator('https://api.example.com/compounds', {
      method: 'GET',
      headers: { Accept: 'application/json' },
      });
      console.log(result.data); // parsed JSON body
      console.log(result.requestHash); // e.g. "a1b2c3d4"
      export async function fetchDecorator(
      url: string,
      options: RequestInit = {},
      ): Promise<Response & { data: unknown; requestHash: string }> {
      const requestHash = await generateRequestHash(url, options);

      const response = await fetch(url, options);

      if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
      }

      const contentType = response.headers.get('content-type') || '';

      if (contentType.includes('application/json')) {
      const data = await response.json();
      return { ...response, data, requestHash };
      }

      if (contentType.includes('text/')) {
      const data = await response.text();
      return { ...response, data, requestHash };
      }

      // For binary data (images, files, etc)
      const data = await response.blob();
      return { ...response, data, requestHash };
      }