ChemPal Documentation - v1.6.0
    Preparing search index...
    • Type guard to validate if an object matches the Chemsavers ProductObject structure. Checks for the presence and correct types of all required product properties including CAS number, inventory level, pricing information, and product identifiers.

      Parameters

      • response: unknown

        Object to validate as ProductObject

      Returns response is ChemsaversProductObject

      Type predicate indicating if response is a valid ProductObject

      // Valid product object
      const validProduct = {
      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 (isValidSearchResponseItem(validProduct)) {
      console.log("Valid product:", validProduct.document.name);
      console.log("Price:", validProduct.document.price);
      console.log("Inventory:", validProduct.document.inventoryLevel);
      }

      // Invalid product (missing document)
      const noDocument = {
      // Missing document property
      CAS: "7647-14-5",
      name: "Sodium Chloride"
      };
      if (!isValidSearchResponseItem(noDocument)) {
      console.error("Invalid product - missing document");
      }

      // Invalid product (missing required properties)
      const missingProps = {
      document: {
      CAS: "7647-14-5",
      name: "Sodium Chloride"
      // Missing other required properties
      }
      };
      if (!isValidSearchResponseItem(missingProps)) {
      console.error("Invalid product - missing required properties");
      }

      // Invalid product (wrong types)
      const wrongTypes = {
      document: {
      CAS: 7647145, // Should be string
      id: 123, // Should be string
      inventoryLevel: "100", // Should be number
      name: 123, // Should be string
      product_id: "12345", // Should be number
      retailPrice: "29.99", // Should be number
      salePrice: "24.99", // Should be number
      price: "24.99", // Should be number
      sku: 123, // Should be string
      upc: 123456789012, // Should be string
      url: 123 // Should be string
      }
      };
      if (!isValidSearchResponseItem(wrongTypes)) {
      console.error("Invalid product - wrong property types");
      }
      export function isValidSearchResponseItem(response: unknown): response is ChemsaversProductObject {
      return v.safeParse(searchResponseItemSchema, response).success;
      }