ChemPal Documentation - v1.6.0
    Preparing search index...
    • Type guard to validate if a response matches the Chemsavers SearchResponse structure. Performs validation of the response object including the results array and its hits, ensuring each hit is a valid ProductObject. This is a comprehensive validation that checks the entire response structure.

      Parameters

      • response: unknown

        Response object to validate

      Returns response is ChemsaversSearchResponse

      Type predicate indicating if response is a valid SearchResponse

      // Valid search response
      const validResponse = {
      results: [
      {
      hits: [
      {
      document: {
      CAS: "7647-14-5",
      id: "prod_123",
      inventoryLevel: 100,
      name: "Sodium Chloride",
      product_id: 12345,
      retailPrice: 29.99,
      salePrice: 24.99,
      price: 24.99,
      sku: "SC-500G",
      upc: "123456789012",
      url: "/products/sodium-chloride"
      }
      }
      ]
      }
      ]
      };

      if (isValidSearchResponse(validResponse)) {
      console.log("Valid search response");
      const firstHit = validResponse.results[0].hits[0];
      console.log("First product:", firstHit.document.name);
      } else {
      console.error("Invalid search response structure");
      }

      // Invalid search response (missing results)
      const noResults = {
      // Missing results property
      };
      if (!isValidSearchResponse(noResults)) {
      console.error("Invalid response - missing results");
      }

      // Invalid search response (empty results)
      const emptyResults = {
      results: [] // Empty array
      };
      if (!isValidSearchResponse(emptyResults)) {
      console.error("Invalid response - empty results");
      }

      // Invalid search response (missing hits)
      const noHits = {
      results: [
      {
      // Missing hits property
      }
      ]
      };
      if (!isValidSearchResponse(noHits)) {
      console.error("Invalid response - missing hits");
      }

      // Invalid search response (invalid hit)
      const invalidHit = {
      results: [
      {
      hits: [
      {
      document: {
      // Invalid product object (missing required properties)
      name: "Sodium Chloride"
      }
      }
      ]
      }
      ]
      };
      if (!isValidSearchResponse(invalidHit)) {
      console.error("Invalid response - invalid hit");
      }
      export function isValidSearchResponse(response: unknown): response is ChemsaversSearchResponse {
      return v.safeParse(searchResponseSchema, response).success;
      }