All files / src/utils/typeGuards carolina.ts

100% Statements 77/77
100% Branches 5/5
100% Functions 5/5
100% Lines 77/77

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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 3001x 1x   1x 1x 1x 1x 1x   1x                                                                                                           1x 1x 10x 10x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x   1x 1x   1x                                                                                                                                             1x 1x 8x 8x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                                                                                           1x 1x 9x 9x   1x 1x 1x 1x 1x 1x 1x   1x   1x 1x   1x                                 1x 1x 6x 6x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                 1x 1x 11x 11x  
import { HttpStatus } from '@/constants/httpStatus';
import * as v from 'valibot';
 
const responseOkSchema = v.object({
  responseStatusCode: v.literal(HttpStatus.OK),
  '@type': v.string(),
  contents: v.record(v.string(), v.unknown()),
});
 
/**
 * Type guard to validate if a response has a valid basic structure for a Carolina search response.
 * Checks for the presence of required properties and correct response status code.
 * This is a basic validation that should be followed by more detailed validation.
 *
 * @category Typeguards
 * @param response - Response object to validate
 * @returns Type predicate indicating if response has valid basic structure
 * @example
 * ```typescript
 * // Valid basic response structure
 * const validResponse = {
 *   responseStatusCode: 200,
 *   "@type": "SearchResponse",
 *   contents: {
 *     ContentFolderZone: [
 *       {
 *         childRules: [
 *           {
 *             // Search result items would be here
 *           }
 *         ]
 *       }
 *     ]
 *   }
 * };
 *
 * if (isResponseOk(validResponse)) {
 *   console.log("Valid basic response structure");
 *   console.log("Status code:", validResponse.responseStatusCode);
 * } else {
 *   console.error("Invalid basic response structure");
 * }
 *
 * // Invalid response (wrong status code)
 * const wrongStatus = {
 *   responseStatusCode: 404,
 *   "@type": "SearchResponse",
 *   contents: {}
 * };
 * if (!isResponseOk(wrongStatus)) {
 *   console.error("Invalid response - wrong status code");
 * }
 *
 * // Invalid response (missing required properties)
 * const missingProps = {
 *   responseStatusCode: 200
 *   // Missing @type and contents
 * };
 * if (!isResponseOk(missingProps)) {
 *   console.error("Invalid response - missing required properties");
 * }
 * ```
 * @source
 */
export function isResponseOk(response: unknown): response is CarolinaSearchResponse {
  return v.safeParse(responseOkSchema, response).success;
}
 
const validSearchResponseSchema = v.object({
  responseStatusCode: v.literal(HttpStatus.OK),
  '@type': v.string(),
  contents: v.object({
    ContentFolderZone: v.pipe(
      v.array(
        v.object({
          childRules: v.pipe(v.array(v.record(v.string(), v.unknown())), v.minLength(1)),
        }),
      ),
      v.minLength(1),
    ),
  }),
});
 
/**
 * Type guard to validate if a response has the complete structure of a Carolina search response.
 * Performs deep validation of the response object including contents, content folder zones,
 * and child rules. This is a more thorough validation than isResponseOk.
 *
 * @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 = {
 *   responseStatusCode: HttpStatus.OK,
 *   "@type": "SearchResponse",
 *   contents: {
 *     ContentFolderZone: [
 *       {
 *         childRules: [
 *           {
 *             "product.productId": "12345",
 *             "product.productName": "Sodium Chloride",
 *             "product.shortDescription": "High purity NaCl",
 *             itemPrice: "29.99",
 *             "product.seoName": "sodium-chloride",
 *             productUrl: "/products/sodium-chloride",
 *             productName: "Sodium Chloride 500g",
 *             qtyDiscountAvailable: false
 *           }
 *         ]
 *       }
 *     ]
 *   }
 * };
 *
 * if (isValidSearchResponse(validResponse)) {
 *   console.log("Valid search response");
 *   const firstItem = validResponse.contents.ContentFolderZone[0].childRules[0];
 *   console.log("First item:", firstItem["product.productName"]);
 * } else {
 *   console.error("Invalid search response structure");
 * }
 *
 * // Invalid search response (empty content folder)
 * const emptyFolder = {
 *   responseStatusCode: 200,
 *   "@type": "SearchResponse",
 *   contents: {
 *     ContentFolderZone: [] // Empty folder
 *   }
 * };
 * if (!isValidSearchResponse(emptyFolder)) {
 *   console.error("Invalid response - empty content folder");
 * }
 *
 * // Invalid search response (missing child rules)
 * const noChildRules = {
 *   responseStatusCode: 200,
 *   "@type": "SearchResponse",
 *   contents: {
 *     ContentFolderZone: [
 *       {
 *         // Missing childRules
 *       }
 *     ]
 *   }
 * };
 * if (!isValidSearchResponse(noChildRules)) {
 *   console.error("Invalid response - missing child rules");
 * }
 * ```
 * @source
 */
export function isValidSearchResponse(response: unknown): response is CarolinaSearchResponse {
  return v.safeParse(validSearchResponseSchema, response).success;
}
 
const searchResultItemSchema = v.object({
  'product.productId': v.string(),
  'product.productName': v.string(),
  'product.shortDescription': v.string(),
  itemPrice: v.string(),
  'product.seoName': v.string(),
  productUrl: v.string(),
  productName: v.string(),
  qtyDiscountAvailable: v.boolean(),
});
 
/**
 * Type guard to validate if an object is a valid Carolina search result item.
 * Checks for the presence and correct types of all required product properties
 * including product ID, name, description, price, and URL.
 *
 * @category Typeguards
 * @param result - Object to validate as SearchResult
 * @returns Type predicate indicating if result is a valid SearchResult
 * @example
 * ```typescript
 * // Valid search result item
 * const validResult = {
 *   "product.productId": "12345",
 *   "product.productName": "Sodium Chloride",
 *   "product.shortDescription": "High purity NaCl",
 *   itemPrice: "29.99",
 *   "product.seoName": "sodium-chloride",
 *   productUrl: "/products/sodium-chloride",
 *   productName: "Sodium Chloride 500g",
 *   qtyDiscountAvailable: false
 * };
 *
 * if (isSearchResultItem(validResult)) {
 *   console.log("Valid search result:", validResult["product.productName"]);
 *   console.log("Price:", validResult.itemPrice);
 *   console.log("URL:", validResult.productUrl);
 * }
 *
 * // Invalid search result (missing required properties)
 * const missingProps = {
 *   "product.productId": "12345",
 *   "product.productName": "Sodium Chloride"
 *   // Missing other required properties
 * };
 * if (!isSearchResultItem(missingProps)) {
 *   console.error("Invalid result - missing required properties");
 * }
 *
 * // Invalid search result (wrong types)
 * const wrongTypes = {
 *   "product.productId": 12345, // Should be string
 *   "product.productName": 123, // Should be string
 *   "product.shortDescription": 123, // Should be string
 *   itemPrice: 29.99, // Should be string
 *   "product.seoName": 123, // Should be string
 *   productUrl: 123, // Should be string
 *   productName: 123, // Should be string
 *   qtyDiscountAvailable: "false" // Should be boolean
 * };
 * if (!isSearchResultItem(wrongTypes)) {
 *   console.error("Invalid result - wrong property types");
 * }
 * ```
 * @source
 */
export function isSearchResultItem(result: unknown): result is CarolinaSearchResult {
  return v.safeParse(searchResultItemSchema, result).success;
}
 
const validProductResponseSchema = v.object({
  contents: v.object({
    MainContent: v.pipe(
      v.array(
        v.object({
          atgResponse: v.record(v.string(), v.unknown()),
        }),
      ),
      v.minLength(1),
    ),
  }),
});
 
/**
 * Validates that a response matches the ProductResponse interface structure.
 *
 * @category Typeguards
 * @param obj - Response object to validate
 * @returns Type predicate indicating if object is a valid ProductResponse
 * @example
 * ```typescript
 * const response = await this.httpGetJson({
 *   path: `/api/rest/cb/product/product-details/${productId}`
 * });
 * if (isValidProductResponse(response)) {
 *   // Process valid product response
 *   console.log(response.product.name);
 * }
 * ```
 * @source
 */
export function isValidProductResponse(obj: unknown): obj is CarolinaProductResponse {
  return v.safeParse(validProductResponseSchema, obj).success;
}
 
const atgResponseSchema = v.object({
  result: v.literal('success'),
  response: v.object({
    response: v.object({
      displayName: v.string(),
      longDescription: v.string(),
      shortDescription: v.string(),
      product: v.string(),
      dataLayer: v.record(v.string(), v.unknown()),
      canonicalUrl: v.string(),
    }),
  }),
});
 
/**
 * Validates that a response matches the ATGResponse interface structure.
 *
 * @category Typeguards
 * @param obj - Response object to validate
 * @returns Type predicate indicating if object is a valid ATGResponse
 * @example
 * ```typescript
 * const response = await this.httpGetJson({
 *   path: `/api/rest/cb/product/product-quick-view/${productId}`
 * });
 * if (isATGResponse(response)) {
 *   // Process valid ATG response
 *   console.log(response.response.response.products[0]);
 * }
 * ```
 * @source
 */
export function isATGResponse(obj: unknown): obj is ATGResponse {
  return v.safeParse(atgResponseSchema, obj).success;
}