All files / src/utils/typeGuards chemsavers.ts

88.09% Statements 37/42
100% Branches 2/2
66.66% Functions 2/3
88.09% Lines 37/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 2341x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                                                                                                                                       1x 1x 26x 26x   1x 1x 1x 1x 1x 1x   1x   1x   1x                                                                                                                                                                                       1x 1x 20x 20x   1x                                   1x 1x              
import * as v from 'valibot';
 
const searchResponseItemSchema = v.object({
  document: v.object({
    //CAS: v.string(),
    id: v.string(),
    inventoryLevel: v.number(),
    name: v.string(),
    product_id: v.number(),
    retailPrice: v.number(),
    salePrice: v.number(),
    price: v.number(),
    sku: v.string(),
    upc: v.string(),
    url: v.string(),
  }),
});
 
/**
 * 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.
 *
 * @category Typeguards
 * @param response - Object to validate as ProductObject
 * @returns Type predicate indicating if response is a valid ProductObject
 * @example
 * ```typescript
 * // 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");
 * }
 * ```
 * @source
 */
export function isValidSearchResponseItem(response: unknown): response is ChemsaversProductObject {
  return v.safeParse(searchResponseItemSchema, response).success;
}
 
const searchResponseSchema = v.object({
  results: v.pipe(
    v.array(
      v.object({
        hits: v.array(searchResponseItemSchema),
      }),
    ),
    v.minLength(1),
  ),
});
 
/**
 * 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.
 *
 * @category Typeguards
 * @param response - Response object to validate
 * @returns Type predicate indicating if response is a valid SearchResponse
 * @example
 * ```typescript
 * // 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");
 * }
 * ```
 * @source
 */
export function isValidSearchResponse(response: unknown): response is ChemsaversSearchResponse {
  return v.safeParse(searchResponseSchema, response).success;
}
 
/**
 * Asserts that a response is a valid Chemsavers SearchResponse.
 * Throws an error if the response is not a valid SearchResponse.
 *
 * @category Typeguards
 * @param response - Response object to validate
 * @throws Error if response is not a valid SearchResponse
 * @example
 * ```typescript
 * try {
 *   assertValidSearchResponse(data);
 *   // data is now typed as ChemsaversSearchResponse
 *   console.log(data.results[0].hits.length);
 * } catch (error) {
 *   console.error("Invalid Chemsavers response:", error.message);
 * }
 * ```
 * @source
 */
export function assertValidSearchResponse(
  response: unknown,
): asserts response is ChemsaversSearchResponse {
  if (!isValidSearchResponse(response)) {
    throw new Error('Invalid search response', { cause: response });
  }
}