Skip to content

feat(magento): port utils foundation (constants, search-criteria, graphql) - #62

Merged
JonasJesus42 merged 1 commit into
mainfrom
JonasJesus42/magento-utils-foundation
Jun 2, 2026
Merged

JonasJesus42 merged 1 commit into
mainfrom
JonasJesus42/magento-utils-foundation

Conversation

@JonasJesus42

@JonasJesus42 JonasJesus42 commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Second PR in the magento-port series (after #61). Lands the pure-utility files that every remaining loader/action will depend on, before the heavier product loaders themselves.

What's included

File Source
magento/client.ts (+ FiltersGraphQL export) Shared with utils/constants
magento/utils/constants.ts (NEW) Verbatim port of deco-cx/apps/magento/utils/constants.ts
magento/utils/stringifySearchCriteria.ts (NEW) Verbatim port
magento/utils/graphql-types.ts (NEW) Subset of deco-cx/apps/magento/utils/clientGraphql/types.ts
magento/utils/graphql.ts (NEW) Verbatim port — signature-preserving
magento/__tests__/stringifySearchCriteria.test.ts (NEW, 4 tests) New
magento/__tests__/graphql.test.ts (NEW, 20 tests) New

Tests

 Test Files  5 passed (5)
      Tests  49 passed (49)

Coverage of the new code:

  • transformSortGraphQL: 4 cases (no sortBy, default ASC, DESC, custom value)
  • transformFilterValueGraphQL: 4 cases (EQUAL/MATCH/RANGE base + RANGE multi-underscore edge)
  • filtersFromUrlGraphQL: 5 cases (defaults, RANGE, MATCH, customFilters layering, empty)
  • filtersFromLoaderGraphQL: 2 cases (undefined → {}, collapses to keyed object)
  • transformFilterGraphQL merge order: 2 cases (collision: loader wins; non-colliding: merged)
  • formatUrlSuffix: 3 cases (strip leading /, append trailing /, no-op)
  • getCustomFields: 4 cases (active=false, overrideList present, fallback, default config)
  • stringifySearchCriteria: 4 cases (top-level scalar, nested object/array, multiple filterGroups, empty)

Why this PR, not just merge into the loader PRs

These utils are shared by all remaining product loaders (PDP, PLP, list, relatedProducts) and most actions. Landing them as a focused, well-tested foundation:

  1. Lets reviewers verify the URL-filter / GraphQL-sort behavior once and reuse the trust across the bigger loader PRs that follow.
  2. Keeps the next PRs small enough to review without test churn (the loaders themselves only test loader-specific paths, not the filter math).
  3. Mirrors how vtex/utils/ was structured — vtexFetch.ts / fetchCache.ts / type files landed before the loaders that consume them.

Next PRs in this series (preview)

# Scope LOC est.
#62 (this) utils foundation ~250 src + ~210 test
Next loaders/product/detailsPage + utils/transform.ts ~800 (transform.ts alone is 756 lines in prod)
Then loaders/product/listingPage + list + relatedProducts ~600
Then loaders/proxy + routes/getRouteType + user + wishlist ~400
Then actions/cart/* + newsletter + wishlist/* + product/stockAlert ~500
Then hooks/* (refactor to react-query) ~400

Test plan

  • bun x vitest run magento/ — 49 tests pass
  • bun x biome check magento/ — clean (5 pre-existing any warnings, not from this PR)
  • package.json exports already cover ./magento/utils/* — no exports-table edit needed
  • Downstream: granadobr-tanstack adopts these utils when the next loader PR (detailsPage) lands

🤖 Generated with Claude Code


Summary by cubic

Ports the Magento utils foundation (constants, GraphQL helpers, and REST search-criteria) to unblock upcoming product loaders. Adds small, pure, well-tested utilities shared by PDP, PLP, list, and relatedProducts.

  • New Features
    • Added magento/utils/constants.ts: URL_KEY, stock availability strings, DEFAULT_GRAPHQL_FILTERS, removable URL params, cart total field names, cookie names.
    • Added magento/utils/graphql.ts: transformSortGraphQL, transformFilterGraphQL, filtersFromUrlGraphQL, filtersFromLoaderGraphQL, transformFilterValueGraphQL, formatUrlSuffix, getCustomFields.
    • Added magento/utils/graphql-types.ts: ProductFilterInput, Filter*TypeInput, ProductSortInput, ProductSort, FilterProps, CustomFields.
    • Added magento/utils/stringifySearchCriteria.ts to flatten REST searchCriteria into bracketed query params.
    • Extended magento/client.ts with FiltersGraphQL type for URL-to-GraphQL filter mapping.
    • New tests for all helpers (49 total passing).

Written for commit 0d00197. Summary will update on new commits.

Review in cubic

…phql)

Second PR in the magento-port series. Lands the pure-utility files
that every remaining loader/action will depend on, before the heavier
product loaders themselves.

What's included (5 source files, 1 test pair = 2 files, 0 wire-ups
needed in apps-start beyond the existing `./magento/utils/*` export):

  magento/client.ts
    + export interface FiltersGraphQL — URL search-param filter mapping
      (value: Magento attribute slug, type: EQUAL|MATCH|RANGE). Lives
      with the rest of the config types so utils/constants.ts and
      utils/graphql.ts share one source of truth.

  magento/utils/constants.ts (NEW)
    Verbatim port of deco-cx/apps/magento/utils/constants.ts:
      - URL_KEY: PDP slug attribute name
      - IN_STOCK / OUT_OF_STOCK: schema.org availability strings
      - DEFAULT_GRAPHQL_FILTERS: the 31-entry array of attribute/operator
        pairs that filtersFromUrlGraphQL crosses against URL params
      - REMOVABLE_URL_SEARCHPARAMS: keys stripped before forwarding URLs
      - Cart totals field names (GRAND_TOTAL/SUBTOTAL/DISCOUNT_AMOUNT/…)
      - Cookie names (SESSION_COOKIE/CUSTOMER_COOKIE/CART_COOKIE/
        FORM_KEY_COOKIE) — single source of truth so loaders/actions/
        middleware don't drift on string literals.

  magento/utils/stringifySearchCriteria.ts (NEW)
    Verbatim port. Flattens a nested Magento REST searchCriteria object
    into the bracketed query-string keys the API requires
    (searchCriteria[filterGroups][0][filters][0][field]=…).

  magento/utils/graphql-types.ts (NEW)
    Subset of deco-cx/apps/magento/utils/clientGraphql/types.ts —
    the input types graphql.ts produces. Extended as more loaders
    land. ProductFilterInput / FilterEqualTypeInput / FilterMatchType-
    Input / FilterRangeTypeInput / ProductSortInput / ProductSort /
    FilterProps / CustomFields.

  magento/utils/graphql.ts (NEW)
    Verbatim port (signature-preserving):
      - transformSortGraphQL({sortBy, order}) → ProductSortInput
      - filtersFromUrlGraphQL(url, customFilters?) → ProductFilterInput
        (URL params × DEFAULT_GRAPHQL_FILTERS + customFilters)
      - filtersFromLoaderGraphQL(fromLoader?) → ProductFilterInput
      - transformFilterGraphQL(url, customFilters?, fromLoader?) →
        merged ProductFilterInput (loader filters override URL on
        collision)
      - transformFilterValueGraphQL(value, "EQUAL"|"MATCH"|"RANGE") →
        typed filter input (RANGE splits on first underscore)
      - formatUrlSuffix(str) → normalize for Magento urlResolver
        (strip leading "/", ensure trailing "/")
      - getCustomFields(CustomFields, fallback?) → resolved attribute
        list for product projection

Tests (24 new, all passing):

  magento/__tests__/stringifySearchCriteria.test.ts (4 tests)
    - top-level scalar flattening
    - nested object/array path style
    - multiple filterGroups (OR semantics)
    - empty input

  magento/__tests__/graphql.test.ts (20 tests)
    - transformSortGraphQL: 4 cases (no sortBy, default ASC, DESC,
      custom value)
    - transformFilterValueGraphQL: 4 cases (EQUAL/MATCH/RANGE base +
      RANGE multi-underscore edge case)
    - filtersFromUrlGraphQL: 5 cases (defaults, RANGE, MATCH,
      customFilters layering, empty)
    - filtersFromLoaderGraphQL: 2 cases (undefined → {}, collapses to
      keyed object)
    - transformFilterGraphQL merge order: 2 cases (collision: loader
      wins; non-colliding: merged)
    - formatUrlSuffix: 3 cases (strip leading /, append trailing /,
      no-op when already correct)
    - getCustomFields: 4 cases (active=false, overrideList present,
      fallback, default config)

Total magento suite: 5 files / 49 tests / 191ms.

The `./magento/utils/*` export entry in package.json already covers
the four new util files — no exports-table edit needed in this PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@JonasJesus42
JonasJesus42 requested a review from a team June 2, 2026 21:25
@JonasJesus42
JonasJesus42 merged commit 1013cbc into main Jun 2, 2026
1 of 2 checks passed
@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

🎉 This PR is included in version 2.2.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

JonasJesus42 added a commit that referenced this pull request Jun 2, 2026
…#63)

Third PR in the magento-port series (after #61 scaffold + #62 utils
foundation). Lands the two simplest actions — both are self-contained
HTTP/GraphQL POSTs with no Granado-specific dependencies.

Files (4 new, 1 modified):

  magento/types.ts (modified)
    + NewsletterData              { success, message }
    + ProductStockAlertResponse   { data?: { productStockAlert: ... } }

  magento/actions/newsletter/subscribe.ts (new)
    POSTs to /rest/:site/V1/newsletter/subscribed with the customer
    email and the resolved storeId. Verbatim port of the legacy 3-arg
    loader, but reads config from getMagentoConfig() and uses
    magentoFetch (so auth/origin/Referer headers come along
    automatically on same-origin). Returns null on success:false or
    non-2xx; payload otherwise — matches prod behavior.

  magento/actions/product/stockAlert.ts (new)
    Fires the ProductStockAlert GraphQL mutation against <baseUrl>/
    graphql. The legacy version called ctx.clientGraphql.query with a
    STALE cache hint, but mutations are write-only — no cache effect.
    Port omits the hint; behavior is observationally identical from a
    consumer's perspective. Returns { data: { productStockAlert } } or
    { error: string }.

  magento/__tests__/newsletter-subscribe.test.ts (new — 6 tests)
    - POSTs to encoded path
    - Body shape { email, store_id: number }
    - storeId coerced to number even when CMS holds it as string
    - Returns payload on success
    - Returns null on success:false (Magento failure shape)
    - Returns null on non-2xx HTTP status

  magento/__tests__/product-stockAlert.test.ts (new — 4 tests)
    - POSTs to <baseUrl>/graphql with the mutation body
    - Returns { data: { productStockAlert } } on success
    - Returns { error } when GraphQL payload lacks productStockAlert
    - Returns { error } when fetch throws

Test totals: 7 files / 59 tests passing in ~165ms.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant