Repository navigation
feat(api): Migrate to VTEX Intelligent Search V1 API with caching - #3376
salesfelipe wants to merge 7 commits into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
WalkthroughAdds 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. ChangesVTEX Search API and Client Refactoring
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
packages/api/src/platforms/vtex/loaders/sku.ts (1)
48-50: ⚖️ Poor tradeoff
maxBatchSizenow controls parallel request count, not batch query size.Previously, batch size limited a single query with multiple SKUs. Now
productsByIdentifierfires one request per SKU, somaxBatchSize: 99means up to 99 parallel HTTP calls. Consider whether this is acceptable for your rate limits, or add chunking/concurrency control inproductsByIdentifier.🤖 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 valueRedundant nullish coalescing with
undefined.Lines 109-114 use
?? undefinedwhich is unnecessary—accessing a missing property already yieldsundefined.♻️ 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 valueGuard URI decoding in VTEX searchPath helpers
encodeSafeURIandremoveDiacriticsFromURLcalldecodeURI/decodeURIComponentwithout a try/catch, so malformed inputs can throw.extractPickupPointIdFromPathShippingFacetalready catchesdecodeURIComponent(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 tradeoffAvoid unbounded parallel VTEX product hydration in
productsByIdentifier
productsByIdentifierissues onefetchProductHTTP call per entry invaluesviaPromise.all, with no concurrency cap.- Call sites can batch up to
first(cross-selling slices tofirst) andgetSkuLoaderusesDataLoaderwithmaxBatchSize: 99, which can translate to ~99 concurrent/api/intelligent-search/v1/productsrequests per loader batch.- Since the client calls
/api/intelligent-search/v1/productswith a singlefield+valueper request, prefer chunking + controlled concurrency (e.g.,p-limit) insideproductsByIdentifier(or around callers), similar to howp-limitis 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
📒 Files selected for processing (12)
packages/api/src/platforms/vtex/clients/search/index.tspackages/api/src/platforms/vtex/loaders/sku.tspackages/api/src/platforms/vtex/resolvers/query.tspackages/api/src/platforms/vtex/utils/searchPath.tspackages/api/src/platforms/vtex/utils/segment.tspackages/api/test/integration/mutations.test.tspackages/api/test/integration/queries.test.tspackages/api/test/mocks/AllProductsQuery.tspackages/api/test/mocks/ProductQuery.tspackages/api/test/mocks/RedirectQuery.tspackages/api/test/mocks/SearchQuery.tspackages/api/test/mocks/ValidateCartMutation.ts
| query: `sku:${skuIds.join(';')}`, | ||
| page: 0, | ||
| count: skuIds.length, | ||
| const products = await clients.search.productsByIdentifier({ |
There was a problem hiding this comment.
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.
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/graphql-utils
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
There was a problem hiding this comment.
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 liftKeep
productsByIdentifierpositional 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 winDon't swallow
/productstransport 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 intoproductsByIdentifier, 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
📒 Files selected for processing (3)
packages/api/src/platforms/vtex/clients/search/index.tspackages/api/src/platforms/vtex/utils/intelligentSearchRequest.tspackages/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( |
There was a problem hiding this comment.
Created this helper function that can be reused into multiple contexts and will help with the overall migration
| } | ||
| } | ||
|
|
||
| function normalizePickupInPointShippingFacets( |
There was a problem hiding this comment.
@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.
## 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]>
Summary
This PR migrates the
@faststore/apisearch client from the legacy/api/io/_v/api/intelligent-searchproxy 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 countSegment Cookie Handling: Extract and parse the
vtex_segmentcookie to pass segment data as query parameters:sc)regionId)productClusterId)Dedicated PDP Endpoint: Single product fetches now use the
/v1/productsendpoint:fetchProduct- Fetch a single product by field (id, sku, slug, etc.)productsByIdentifier- Fan out parallel calls for multiple products/SKUsCross-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 extractionpackages/api/src/platforms/vtex/utils/searchPath.ts- Path building and facet utilitiesBreaking Changes
None - the GraphQL API remains unchanged. This is an internal implementation change.
Test plan
Made with Cursor
Summary by CodeRabbit
New Features
Refactor
Tests