Skip to content

Conversation

@aline-pereira
Copy link
Contributor

@aline-pereira aline-pereira commented Nov 26, 2025

What is this Contribution About?

Some stores are receiving many VTEX timeout errors (HttpError 400: "Can't create search criteria! Error: Invalid Parameter, skuId should be Int64.)
Possibly invalid skuids were being passed to the VTEX API.
image

Added validation to filter out invalid IDs before sending to the VTEX API.

Summary by CodeRabbit

  • Bug Fixes
    • Product list selection now filters out invalid (non-numeric) IDs and trims whitespace when selecting by SKU or Product IDs, ensuring only valid IDs are used in queries.
    • Cache keys now use the sanitized, consistently ordered ID lists, preventing mismatches and improving cache reliability.
    • Preserves existing single-entry mapping behavior and formatting; only ID handling was tightened.

✏️ Tip: You can customize this high-level summary in your review settings.

@github-actions
Copy link
Contributor

Tagging Options

Should a new tag be published when this PR is merged?

  • 👍 for Patch 0.133.10 update
  • 🎉 for Minor 0.134.0 update
  • 🚀 for Major 1.0.0 update

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 26, 2025

Walkthrough

Adds a sanitizer that trims and retains only numeric IDs for SKU and Product ID selection, applies it when building queries and cache keys (sorted), and updates where sanitized ID lists are used in query construction.

Changes

Cohort / File(s) Summary
ID sanitization, query & cacheKey updates
vtex/loaders/legacy/productList.ts
Introduced sanitizeNumericIds(ids) to trim and filter numeric-only IDs; applied to props.ids (SKU path) and props.productIds (Product path) before building fq filters and queries; cacheKey now uses sorted sanitized SKU/Product ID lists; minor control-flow/formatting adjustments around ID handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Verify sanitizeNumericIds trims and excludes non-numeric/empty values.
  • Confirm sanitized lists are consistently used in query construction and cacheKey.
  • Check behavior when sanitized lists become empty and any downstream logic relying on ID presence.

Poem

🐰 I nibbled spaces, chased stray chars away,

Numbers hopped home and decided to stay.
Queries now tidy, cache keys aligned,
A rabbit's small fix — neat IDs, refined. 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding validation to VTEX SKU IDs, which directly addresses the changeset's core purpose of filtering invalid IDs.
Description check ✅ Passed The description addresses the 'What is this Contribution About?' section with clear context about the issue and solution, but lacks the optional Issue Link, Loom Video, and Demonstration Link sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/invalid-vtex-skuid

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
vtex/loaders/legacy/productList.ts (1)

135-143: SKU ID validation is solid; consider behavior when everything gets filtered out

The new filtering logic for skuIds (trimming and enforcing ^\d+$) is a good match for VTEX’s Int64 expectation and should eliminate the 400s from invalid SKUs.

Two small follow‑ups you may want to consider:

  • When all provided SKU IDs are invalid/whitespace, skuIds becomes empty but we still:
    • Leave params.fq empty, and
    • Call VTEX with _from = 0, _to = 0.
      That likely returns some arbitrary first product instead of “no results”. If you’d rather treat “no valid SKUs” as “no products”, you could short‑circuit before making the VTEX call (e.g., return null/[] from the loader) or encode a sentinel range that the caller interprets as “skip request”.
  • You’re trimming twice (skuId.trim() in the filter and again when building fq). A tiny DRY/readability improvement is to normalize once and reuse:
const sanitizeNumericIds = (ids?: string[]) =>
  (ids ?? [])
    .map((id) => id.trim())
    .filter((id) => id && /^\d+$/.test(id));

if (isSKUIDProps(props)) {
  const skuIds = sanitizeNumericIds(props.ids);

  skuIds.forEach((skuId) => params.fq.push(`skuId:${skuId}`));
  params._from = 0;
  params._to = Math.max(skuIds.length - 1, 0);

  return params;
}

You could also reuse sanitizeNumericIds in cacheKey so different spellings of the same IDs (whitespace, leading zeros, etc.) map to the same cache entry.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9bf0b5a and 99f279e.

📒 Files selected for processing (1)
  • vtex/loaders/legacy/productList.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
vtex/loaders/legacy/productList.ts

[error] 150-152: Deno fmt --check failed: Found 1 not formatted file in 2081 files. Apply formatting (deno fmt) and re-run the CI.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
vtex/loaders/legacy/productList.ts (2)

141-148: Consider handling the empty sanitized IDs case.

If all SKU IDs are invalid and sanitizeNumericIds returns an empty array, the code will still make a VTEX API request with no fq filters and _to = 0. This might return unexpected results.

Consider adding an early return or empty result when no valid IDs remain:

 if (isSKUIDProps(props)) {
   const skuIds = sanitizeNumericIds(props.ids);
+  
+  if (skuIds.length === 0) {
+    // Return params that will result in no products
+    params._from = 0;
+    params._to = 0;
+    return params;
+  }

   skuIds.forEach((skuId) => params.fq.push(`skuId:${skuId}`));

Alternatively, the loader could return an empty array immediately when no valid IDs are provided, avoiding the API call entirely.


127-130: Inconsistency: Raw IDs used for SKU selection and sorting after sanitization.

The fromProps function sanitizes IDs before querying VTEX (lines 142, 152), but preferredSKU (line 128) and sortProducts (lines 228, 234) still use the raw, unsanitized IDs from props. This creates an inconsistency:

  • VTEX returns products matching sanitized IDs
  • preferredSKU looks for SKUs using raw IDs (including invalid ones)
  • sortProducts attempts to sort using raw IDs (including invalid ones)

Impact: If invalid IDs are provided, preferredSKU won't find matches and will fall back to items[0]. Invalid IDs passed to sortProducts won't match any products, potentially affecting the sort order.

Recommendation: Store the sanitized IDs at a broader scope and use them consistently:

const loader = async (
  expandedProps: Props,
  req: Request,
  ctx: AppContext,
): Promise<Product[] | null> => {
  const props = expandedProps.props ??
    (expandedProps as unknown as Props["props"]);
  
  // Store sanitized IDs for consistent use
  let sanitizedIds: string[] | undefined;
  if (isSKUIDProps(props)) {
    sanitizedIds = sanitizeNumericIds(props.ids);
  } else if (isProductIDProps(props)) {
    sanitizedIds = sanitizeNumericIds(props.productIds);
  }
  
  // ... rest of loader
  
  // Update preferredSKU to accept sanitized IDs
  const fetchedSkus = new Set(sanitizedIds ?? []);
  
  // Update sortProducts calls to use sanitized IDs
  if (isSKUIDProps(props)) {
    products = sortProducts(products, sanitizedIds || [], "sku");
  }
  
  if (isProductIDProps(props)) {
    products = sortProducts(products, sanitizedIds || [], "inProductGroupWithID");
  }

Also applies to: 228-229, 232-236

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 455910d and 05b9bd7.

📒 Files selected for processing (1)
  • vtex/loaders/legacy/productList.ts (4 hunks)
🔇 Additional comments (2)
vtex/loaders/legacy/productList.ts (2)

121-125: LGTM! Clean helper for ID sanitization.

The sanitizeNumericIds helper correctly filters out invalid IDs and trims whitespace, which should prevent the VTEX "Invalid Parameter, skuId should be Int64" errors mentioned in the PR objectives.


311-319: LGTM! Cache key now consistent with sanitized IDs.

The cache key generation now uses sanitizeNumericIds and sorts the results, ensuring that cache entries match the actual IDs sent to VTEX. This addresses the inconsistency flagged in previous reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants