Skip to content

feat(api): Migrate to VTEX Intelligent Search V1 API with caching - #3376

Closed
salesfelipe wants to merge 7 commits into
v3from
feat/new-is-api-v3
Closed

salesfelipe wants to merge 7 commits into
v3from
feat/new-is-api-v3

Conversation

@salesfelipe

@salesfelipe salesfelipe commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR migrates the @faststore/api search client from the legacy /api/io/_v/api/intelligent-search proxy to the new cached V1 Intelligent Search API endpoints.

Key Changes

  • New API Endpoints: All search methods now use the V1 endpoints with built-in caching:

    • /api/intelligent-search/v1/product-search/ - Product search
    • /api/intelligent-search/v1/facets/ - Facets
    • /api/intelligent-search/v1/products - Single product details (PDP)
    • /api/intelligent-search/v1/search-suggestions - Search suggestions
    • /api/intelligent-search/v1/top-searches - Top searches
    • /api/intelligent-search/v1/catalog-count/ - Product count
  • Segment Cookie Handling: Extract and parse the vtex_segment cookie to pass segment data as query parameters:

    • Sales channel (sc)
    • Region ID (regionId)
    • Locale
    • Shipping/geo params (zip-code, coordinates, pickupPoint, etc.)
    • UTM params (utmSource, utmCampaign, utmiCampaign)
    • Campaigns and price tables
    • Product cluster IDs (productClusterId)
  • Dedicated PDP Endpoint: Single product fetches now use the /v1/products endpoint:

    • fetchProduct - Fetch a single product by field (id, sku, slug, etc.)
    • productsByIdentifier - Fan out parallel calls for multiple products/SKUs
  • Cross-selling Optimization: Cross-selling product hydration now uses productsByIdentifier (PDP endpoint) instead of the search endpoint for better cache utilization.

New Files

  • packages/api/src/platforms/vtex/utils/segment.ts - Segment cookie parsing and parameter extraction
  • packages/api/src/platforms/vtex/utils/searchPath.ts - Path building and facet utilities

Breaking Changes

None - the GraphQL API remains unchanged. This is an internal implementation change.

Test plan

  • All existing unit tests pass
  • All existing integration tests pass
  • Manual testing in a demo store
  • Verify product search returns correct results
  • Verify facets are correctly returned
  • Verify PDP loads product details
  • Verify cart validation works with SKU loading
  • Verify cross-selling products load correctly

Made with Cursor

Summary by CodeRabbit

  • New Features

    • Identifier-based product lookup by ID, SKU, slug, EAN, or reference for direct product retrieval.
  • Refactor

    • Search, suggestions and counts routed to v1 intelligent-search endpoints with a centralized request/parameter builder.
    • Improved locale, region and segment handling plus visibility/sponsored controls for more accurate results.
  • Tests

    • Added unit tests and updated integration mocks to reflect v1 request/response behavior.

@salesfelipe
salesfelipe requested a review from a team as a code owner June 2, 2026 17:28
@salesfelipe
salesfelipe requested review from emersonlaurentino and lemagnetic and removed request for a team June 2, 2026 17:28
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 780fe18e-b42a-45f7-ab1c-eab28ae8e85b

📥 Commits

Reviewing files that changed from the base of the PR and between fc70bdf and 33541e4.

📒 Files selected for processing (4)
  • packages/api/src/platforms/vtex/clients/search/index.ts
  • packages/api/src/platforms/vtex/resolvers/query.ts
  • packages/api/src/platforms/vtex/utils/intelligentSearchRequest.ts
  • packages/api/test/unit/platforms/vtex/utils/intelligentSearchRequest.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/api/src/platforms/vtex/resolvers/query.ts
  • packages/api/test/unit/platforms/vtex/utils/intelligentSearchRequest.test.ts
  • packages/api/src/platforms/vtex/clients/search/index.ts
  • packages/api/src/platforms/vtex/utils/intelligentSearchRequest.ts

Walkthrough

Adds buildIntelligentSearchRequest and parseSegmentCookie to compose intelligent-search v1 paths/params from segments and facets; refactors VTEX search client to add identifier-based fetchProduct/productsByIdentifier, routes search/count/suggestions to v1 endpoints, and updates resolvers, SKU loader, tests, and mocks to new endpoints and payloads.

Changes

VTEX Search API and Client Refactoring

Layer / File(s) Summary
Segment Parsing and Intelligent Search Request Builder
packages/api/src/platforms/vtex/utils/intelligentSearchRequest.ts
New module exports types and buildIntelligentSearchRequest plus parseSegmentCookie; it decodes vtex_segment cookies, extracts shipping/pickup facets, normalizes attribute paths, and builds endpoint-specific query params for product-search, facets, products, search-suggestions, top-searches, and catalog-count.
Search Client with Identifier-Based Methods
packages/api/src/platforms/vtex/clients/search/index.ts
Client delegates path/params to buildIntelligentSearchRequest, re-exports ProductIdentifierField/Sort, adds FetchProductArgs and ProductsByIdentifierArgs, implements fetchProduct (returns `Product
Query Resolvers Using Identifier Fetching
packages/api/src/platforms/vtex/resolvers/query.ts
Query.product now calls fetchProduct({ field: 'id', value }); Query.search builds searchArgs, handles cross-selling by fetching IDs then hydrating with productsByIdentifier, and Query.products directly uses productsByIdentifier.
SKU Loader Using Batch Identifier Fetch
packages/api/src/platforms/vtex/loaders/sku.ts
Batch SKU loader switched to clients.search.productsByIdentifier({ field: 'sku', values: skuIds }) instead of composing sku: query strings.
Integration Tests and Fixture Updates
packages/api/test/integration/*, packages/api/test/mocks/*
Mocks and integration tests updated to point to /api/intelligent-search/v1/..., productSearchFetch → pdpFetch, search-wrapper mock shapes replaced with PDP-style product payloads, and test fetch expectations adjusted to handle v1 products calls (SKU param extraction and adjusted call counts).
Unit Test Suite for Request Builder
packages/api/test/unit/platforms/vtex/utils/intelligentSearchRequest.test.ts
New tests cover pagination, defaults from vtex_segment, shipping/pickup normalization, facet inclusion/exclusion rules, endpoint-specific behavior, optional flags, and toString() serialization; includes real vtex_segment cookie examples.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

enhancement

Suggested reviewers

  • renatomaurovtex
  • eduardoformiga
  • emersonlaurentino

"Segment decoded, facets set to flight,
Builder crafts paths and query strings right.
Fetch by id or batch—products appear,
Tests and mocks now match v1's new sphere.
A tidy refactor; search flows take flight ✨"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: migration to VTEX Intelligent Search V1 API with caching support, which is the primary focus across all modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/new-is-api-v3

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.

@salesfelipe salesfelipe self-assigned this Jun 2, 2026
@codesandbox-ci

codesandbox-ci Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (4)
packages/api/src/platforms/vtex/loaders/sku.ts (1)

48-50: ⚖️ Poor tradeoff

maxBatchSize now controls parallel request count, not batch query size.

Previously, batch size limited a single query with multiple SKUs. Now productsByIdentifier fires one request per SKU, so maxBatchSize: 99 means up to 99 parallel HTTP calls. Consider whether this is acceptable for your rate limits, or add chunking/concurrency control in productsByIdentifier.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/src/platforms/vtex/loaders/sku.ts` around lines 48 - 50, The
DataLoader is configured with maxBatchSize: 99 which now controls concurrent
requests because productsByIdentifier issues one HTTP call per SKU; update this
by either reducing maxBatchSize to a safe concurrency number that fits VTEX rate
limits or implement explicit chunking/concurrency control inside
productsByIdentifier (e.g., process SKUs in batches and await each batch) and
keep DataLoader's maxBatchSize aligned with that logic; locate the DataLoader
creation and the productsByIdentifier function to make the change and ensure you
limit parallel HTTP calls to an acceptable value.
packages/api/src/platforms/vtex/utils/segment.ts (1)

67-119: 💤 Low value

Redundant nullish coalescing with undefined.

Lines 109-114 use ?? undefined which is unnecessary—accessing a missing property already yields undefined.

♻️ Simplify by removing redundant coalescing
-      utmSource: (segment.utm_source as string | undefined) ?? undefined,
-      utmCampaign: (segment.utm_campaign as string | undefined) ?? undefined,
-      utmiCampaign: (segment.utmi_campaign as string | undefined) ?? undefined,
+      utmSource: segment.utm_source as string | undefined,
+      utmCampaign: segment.utm_campaign as string | undefined,
+      utmiCampaign: segment.utmi_campaign as string | undefined,
       campaigns:
         typeof segment.campaigns === 'string' ? segment.campaigns : undefined,
-      priceTables: (segment.priceTables as string | undefined) ?? undefined,
+      priceTables: segment.priceTables as string | undefined,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/src/platforms/vtex/utils/segment.ts` around lines 67 - 119, In
extractSegmentData, remove the redundant "?? undefined" coalescing when
assigning optional fields inside segmentParams (currently used for utmSource,
utmCampaign, utmiCampaign, priceTables) because a missing property already
yields undefined; update the assignments in the segmentParams object (utmSource,
utmCampaign, utmiCampaign, priceTables) to simply use the casted values (e.g.,
segment.utm_source as string | undefined) and leave campaigns logic unchanged.
packages/api/src/platforms/vtex/utils/searchPath.ts (1)

4-12: 💤 Low value

Guard URI decoding in VTEX searchPath helpers

encodeSafeURI and removeDiacriticsFromURL call decodeURI/decodeURIComponent without a try/catch, so malformed inputs can throw. extractPickupPointIdFromPathShippingFacet already catches decodeURIComponent(rawId), so consider adding the same defensive fallback (or clearly asserting upstream input is URI-safe) in these two helpers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/src/platforms/vtex/utils/searchPath.ts` around lines 4 - 12,
Guard decodeURI/decodeURIComponent calls in encodeSafeURI and
removeDiacriticsFromURL by wrapping the decode step in a try/catch and falling
back to the original input when decoding fails (similar to
extractPickupPointIdFromPathShippingFacet); e.g., in encodeSafeURI, try decoding
uri and if it throws use uri as-is before calling encodeURI, and in
removeDiacriticsFromURL, try decodeURIComponent(url) and if it throws use url
as-is before .normalize and replace, preserving current output behavior on valid
input.
packages/api/src/platforms/vtex/clients/search/index.ts (1)

312-327: ⚖️ Poor tradeoff

Avoid unbounded parallel VTEX product hydration in productsByIdentifier

  • productsByIdentifier issues one fetchProduct HTTP call per entry in values via Promise.all, with no concurrency cap.
  • Call sites can batch up to first (cross-selling slices to first) and getSkuLoader uses DataLoader with maxBatchSize: 99, which can translate to ~99 concurrent /api/intelligent-search/v1/products requests per loader batch.
  • Since the client calls /api/intelligent-search/v1/products with a single field + value per request, prefer chunking + controlled concurrency (e.g., p-limit) inside productsByIdentifier (or around callers), similar to how p-limit is used elsewhere in VTEX.
const productsByIdentifier = async ({ field, values, showInvisibleItems, hideUnavailableItems }: ProductsByIdentifierArgs): Promise<Product[]> => {
  const productsResult = await Promise.all(
    values.map((value) =>
      fetchProduct({ field, value, hideUnavailableItems, showInvisibleItems })
    )
  )

  return productsResult.filter((product): product is Product => product !== null)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/src/platforms/vtex/clients/search/index.ts` around lines 312 -
327, productsByIdentifier currently fires fetchProduct for every value in
parallel via Promise.all which can create many concurrent VTEX HTTP calls;
change productsByIdentifier to limit concurrency (e.g., use p-limit or internal
chunking) so only a bounded number of fetchProduct calls run at once, then
collect and filter non-null Product results; reference the productsByIdentifier
function and fetchProduct helper and ensure the concurrency cap aligns with
existing VTEX usage (e.g., reuse p-limit with the same limit used elsewhere or a
sensible default) and preserve the returned Promise<Product[]> behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/src/platforms/vtex/clients/search/index.ts`:
- Around line 282-310: The fetchProduct function currently swallows all errors
by catching everything and returning null, losing failure context; update
fetchProduct to catch errors from fetchAPI (the call to fetchAPI in
fetchProduct) and distinguish 404/not-found responses from other errors: if the
response indicates a not-found, return null, otherwise log the error (use an
existing logger or throw the error) including the fetchAPI error details and any
request params, or rethrow non-404 errors so callers can handle retries/alerts;
reference the fetchProduct function and the fetchAPI call to locate where to add
error handling and logging.

---

Nitpick comments:
In `@packages/api/src/platforms/vtex/clients/search/index.ts`:
- Around line 312-327: productsByIdentifier currently fires fetchProduct for
every value in parallel via Promise.all which can create many concurrent VTEX
HTTP calls; change productsByIdentifier to limit concurrency (e.g., use p-limit
or internal chunking) so only a bounded number of fetchProduct calls run at
once, then collect and filter non-null Product results; reference the
productsByIdentifier function and fetchProduct helper and ensure the concurrency
cap aligns with existing VTEX usage (e.g., reuse p-limit with the same limit
used elsewhere or a sensible default) and preserve the returned
Promise<Product[]> behavior.

In `@packages/api/src/platforms/vtex/loaders/sku.ts`:
- Around line 48-50: The DataLoader is configured with maxBatchSize: 99 which
now controls concurrent requests because productsByIdentifier issues one HTTP
call per SKU; update this by either reducing maxBatchSize to a safe concurrency
number that fits VTEX rate limits or implement explicit chunking/concurrency
control inside productsByIdentifier (e.g., process SKUs in batches and await
each batch) and keep DataLoader's maxBatchSize aligned with that logic; locate
the DataLoader creation and the productsByIdentifier function to make the change
and ensure you limit parallel HTTP calls to an acceptable value.

In `@packages/api/src/platforms/vtex/utils/searchPath.ts`:
- Around line 4-12: Guard decodeURI/decodeURIComponent calls in encodeSafeURI
and removeDiacriticsFromURL by wrapping the decode step in a try/catch and
falling back to the original input when decoding fails (similar to
extractPickupPointIdFromPathShippingFacet); e.g., in encodeSafeURI, try decoding
uri and if it throws use uri as-is before calling encodeURI, and in
removeDiacriticsFromURL, try decodeURIComponent(url) and if it throws use url
as-is before .normalize and replace, preserving current output behavior on valid
input.

In `@packages/api/src/platforms/vtex/utils/segment.ts`:
- Around line 67-119: In extractSegmentData, remove the redundant "?? undefined"
coalescing when assigning optional fields inside segmentParams (currently used
for utmSource, utmCampaign, utmiCampaign, priceTables) because a missing
property already yields undefined; update the assignments in the segmentParams
object (utmSource, utmCampaign, utmiCampaign, priceTables) to simply use the
casted values (e.g., segment.utm_source as string | undefined) and leave
campaigns logic unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ef898b63-13a1-4864-b4d0-66c888bc46b0

📥 Commits

Reviewing files that changed from the base of the PR and between caf8c97 and f287981.

📒 Files selected for processing (12)
  • packages/api/src/platforms/vtex/clients/search/index.ts
  • packages/api/src/platforms/vtex/loaders/sku.ts
  • packages/api/src/platforms/vtex/resolvers/query.ts
  • packages/api/src/platforms/vtex/utils/searchPath.ts
  • packages/api/src/platforms/vtex/utils/segment.ts
  • packages/api/test/integration/mutations.test.ts
  • packages/api/test/integration/queries.test.ts
  • packages/api/test/mocks/AllProductsQuery.ts
  • packages/api/test/mocks/ProductQuery.ts
  • packages/api/test/mocks/RedirectQuery.ts
  • packages/api/test/mocks/SearchQuery.ts
  • packages/api/test/mocks/ValidateCartMutation.ts

query: `sku:${skuIds.join(';')}`,
page: 0,
count: skuIds.length,
const products = await clients.search.productsByIdentifier({

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

While fetching this info, do we really need to calculate the price and availability? Because if we don't we could skip the simutations, which could boost the overrall performance.

@pkg-pr-new

pkg-pr-new Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/cli

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/components

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/core

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/graphql-utils

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/lighthouse

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/sdk

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/ui

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

commit: dec27de

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/api/src/platforms/vtex/clients/search/index.ts (1)

179-181: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Keep productsByIdentifier positional for batch callers.

Filtering out misses changes the result length and index mapping. The stacked SKU loader now uses this method as its batch function, so the nth returned product can stop corresponding to the nth requested identifier.

Return a same-length array (for example Array<Product | null>) or a keyed result and let the caller decide how to handle misses.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/src/platforms/vtex/clients/search/index.ts` around lines 179 -
181, The current filter call in productsByIdentifier removes nulls from
productsResult, breaking positional correspondence for batch callers (e.g., the
stacked SKU loader); change productsByIdentifier to return a same-length array
so callers can map indices to requests—preserve nulls instead of filtering
(return Array<Product | null> or a keyed map) by removing the
productsResult.filter(...) and returning the original productsResult with its
null entries intact so the nth element still corresponds to the nth identifier.
♻️ Duplicate comments (1)
packages/api/src/platforms/vtex/clients/search/index.ts (1)

154-159: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't swallow /products transport errors.

This still converts every fetch failure into null, so upstream timeouts/5xxs become "missing product" instead of a retriable error. That also feeds directly into productsByIdentifier, which then drops those failures silently.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/api/src/platforms/vtex/clients/search/index.ts` around lines 154 -
159, The current code in the search client wraps fetchAPI(...) in
Promise.resolve(...).catch(() => null) which turns all transport failures into
null (making timeouts/5xx appear as "missing product"); remove that blanket
.catch and instead let fetchAPI errors propagate so upstream (e.g.
productsByIdentifier) can handle/retry, or if you must swallow only handle
specific "not found" cases by inspecting the response status from fetchAPI and
returning null only for 404; update the return in the function that builds
`${base}/api/intelligent-search/v1/products?${request.params.toString()}` to
either drop the catch entirely or replace it with logic that checks the response
status and only returns null for 404 while rethrowing other errors.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/api/src/platforms/vtex/utils/intelligentSearchRequest.ts`:
- Around line 351-367: resolveSegmentData currently lets cookie-derived
segmentParams.sc and segmentParams.regionId override server defaults; change it
so server defaults (defaults.salesChannel and defaults.regionId) take precedence
(e.g., use defaults?.salesChannel ?? segmentParams.sc and defaults?.regionId ??
segmentParams.regionId) and only fall back to cookie values when defaults are
absent, and/or add a session validation step to reject/ignore vtex_segment
values that don't match the authenticated session; update the sc and regionId
assignments in resolveSegmentData (which calls extractSegmentData) accordingly
so client-supplied vtex_segment cannot overwrite trusted server context.
- Around line 376-400: pathFacets already includes facets with SHIPPING_KEY and
DELIVERY_OPTIONS_KEY, so pushing shippingFacet/deliveryOptionsFacet
unconditionally duplicates them; update the logic in intelligentSearchRequest.ts
to avoid duplicates by initializing withShippingFacets from pathFacets after
filtering out SHIPPING_KEY and DELIVERY_OPTIONS_KEY (or check existence before
push), then conditionally push shippingFacet and deliveryOptionsFacet only if
they are non-null and not already present; keep PATH_EXCLUDED_KEYS,
SHIPPING_KEY, DELIVERY_OPTIONS_KEY, shippingFacet, deliveryOptionsFacet,
withShippingFacets, and concatSelectedFacets as the reference symbols to locate
and modify the code.
- Around line 327-338: The buildAttributePath reducer currently only replaces
the first space or "%20" in facet values, causing multi-word facets to remain
partially encoded; update the replacement on the processed value in
buildAttributePath (the expression using
removeDiacriticsFromURL(encodeSafeURI(value)).replace(...)) to replace all
occurrences (use a global replacement for spaces and "%20") so every encoded
space is normalized for the intelligent-search path; keep the existing
special-case handling for key === 'priceRange' and the ft filter logic intact.

In
`@packages/api/test/unit/platforms/vtex/utils/intelligentSearchRequest.test.ts`:
- Around line 187-199: The test 'includes shipping facet in path when not
all-delivery-methods' currently uses toContain and can miss duplicated segments;
change the assertion on request.path (from buildIntelligentSearchRequest) to
compare against the exact expected path string (use toBe/toEqual) rather than
toContain so the test fails when the path is duplicated (ensure you construct
the exact expected path using the same defaults/args used in the test and assert
equality).

---

Outside diff comments:
In `@packages/api/src/platforms/vtex/clients/search/index.ts`:
- Around line 179-181: The current filter call in productsByIdentifier removes
nulls from productsResult, breaking positional correspondence for batch callers
(e.g., the stacked SKU loader); change productsByIdentifier to return a
same-length array so callers can map indices to requests—preserve nulls instead
of filtering (return Array<Product | null> or a keyed map) by removing the
productsResult.filter(...) and returning the original productsResult with its
null entries intact so the nth element still corresponds to the nth identifier.

---

Duplicate comments:
In `@packages/api/src/platforms/vtex/clients/search/index.ts`:
- Around line 154-159: The current code in the search client wraps fetchAPI(...)
in Promise.resolve(...).catch(() => null) which turns all transport failures
into null (making timeouts/5xx appear as "missing product"); remove that blanket
.catch and instead let fetchAPI errors propagate so upstream (e.g.
productsByIdentifier) can handle/retry, or if you must swallow only handle
specific "not found" cases by inspecting the response status from fetchAPI and
returning null only for 404; update the return in the function that builds
`${base}/api/intelligent-search/v1/products?${request.params.toString()}` to
either drop the catch entirely or replace it with logic that checks the response
status and only returns null for 404 while rethrowing other errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: aa14d569-9f64-4399-a9c2-84aa409f9923

📥 Commits

Reviewing files that changed from the base of the PR and between f287981 and 281712b.

📒 Files selected for processing (3)
  • packages/api/src/platforms/vtex/clients/search/index.ts
  • packages/api/src/platforms/vtex/utils/intelligentSearchRequest.ts
  • packages/api/test/unit/platforms/vtex/utils/intelligentSearchRequest.test.ts

* Pure builder for intelligent-search v1 path + query params.
* Callers assemble the full URL: `/api/intelligent-search/v1/${endpoint}/${request.path}?${request.params}`.
*/
export function buildIntelligentSearchRequest(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Created this helper function that can be reused into multiple contexts and will help with the overall migration

}
}

function normalizePickupInPointShippingFacets(

@salesfelipe salesfelipe Jun 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@hiagolcm do you think this will be necessary on Faststore? This was ported from our search-resolver implementation, but not sure if it still aplies to this context.

@lemagnetic
lemagnetic deleted the branch v3 June 8, 2026 13:42
@lemagnetic lemagnetic closed this Jun 8, 2026
hellofanny pushed a commit that referenced this pull request Jun 19, 2026
## Summary

Ports the changes from #3376 (originally opened against `v3`) onto the
`dev` (v4) line.

- Migrates the VTEX search client to the **Intelligent Search V1** API
(`/api/intelligent-search/v1/...`), adding `fetchProduct`,
`productsByIdentifier`, and `productCount`.
- Centralizes request construction (pagination, facets,
segment/region/locale handling) in the new
`utils/intelligentSearchRequest.ts` util, with `parseSegmentCookie` for
segment-aware requests.
- PDP, the `products` resolver, cross-selling, and the SKU loader now
hydrate products via `productsByIdentifier` / `fetchProduct`, honoring
`hideUnavailableItems`.
- Updates integration mocks and tests to match the V1 request/response
shapes; adds unit tests for the request builder.

### v3 → v4 adaptations made while porting
- Kept v4's `GraphqlContext` (the v3 PR used `Context`) and treated
`Options` as the global type rather than importing it.
- Removed the now-unused `IStoreSelectedFacet` import in the search
client.
- Preserved v4's extra `.filter(...)` in the `products` resolver.
- Added explicit `vitest` imports in the new unit test (v4 does not
enable vitest globals).

## Test plan

- [x] `pnpm test:unit` in `packages/api` (26 passed)
- [x] `pnpm test:int` in `packages/api` (44 passed)
- [x] Biome lint clean on changed files
- [ ] Validate in a starter store via the `ci/codesandbox` check

Made with [Cursor](https://cursor.com)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Refactor**
* Migrated product, facets, suggestions, top searches, and product
counting to the latest intelligent-search v1 flow using a shared request
builder for more consistent query construction.
* Added dedicated SKU and identifier-based product retrieval, including
support for cross-selling hydration in a two-step process.
* **Bug Fixes**
* Improved “product not found” handling by tightening fallback
conditions for SKU lookup failures.
* **Tests**
* Updated mocks for the new endpoints and added unit coverage for
request-building behavior and segment/cookie-derived defaults.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor <[email protected]>
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