ChemPal Documentation - v0.0.13-beta.5
    Preparing search index...

    Function getCachableResponse

    • Creates a cacheable response object from a Request and Response pair. This function serializes the response content based on its content type and generates a hash for the request to be used as a cache key.

      Parameters

      • request: Request

        The original Request object

      • response: Response

        The Response object to be cached

      Returns Promise<CacheResponse>

      A Promise that resolves to a CacheResponse object containing: - hash: The RequestHashObject with request details and hash - data: A SerializedResponse containing the content type and serialized content

      const request = new Request('https://api.example.com/data');
      const response = await fetch(request);
      const cacheResponse = await getCachableResponse(request, response);
      // Returns: {
      // hash: {
      // hash: '01b5190db0c0f8c232d2ad4d8957d5f4',
      // file: 'api.example.com/01b5190db0c0f8c232d2ad4d8957d5f4.json',
      // url: URL object
      // },
      // data: {
      // contentType: 'application/json',
      // content: '{"serialized":"content"}'
      // }
      // }
      export async function getCachableResponse(
      request: Request,
      response: Response,
      ): Promise<CacheResponse> {
      const reqHash = getRequestHash(request);

      // Generate a serialized object to be saved
      const dataType = contentType.parse(response.headers.get("content-type")?.toString() ?? "");

      const serializedResponse: SerializedResponse = {
      contentType: dataType.type,
      };

      const clonedResponse = response.clone();

      if (serializedResponse.contentType === "application/json") {
      // Json gets stringified
      serializedResponse.content = serialize(JSON.stringify(await clonedResponse.json()));
      } else {
      // Everything else is treated as text
      serializedResponse.content = serialize(await clonedResponse.text());
      }

      return {
      hash: reqHash,
      data: serializedResponse,
      } satisfies CacheResponse;
      }