Repository navigation
Carry shopper product customization through add-to-cart - #1534
ajaynes-godaddy wants to merge 4 commits into
Conversation
AIROBUILD-9325
AddToCartItemInput was narrowed to { skuId, name, quantity }, so shopper
customization (uploaded designs, add-ons, metafields) never reached
order-api or checkout. Widen the cart contract end-to-end:
- order-subgraph.ts: add optional details (productAssetUrl,
selectedAddons) and metafields to AddToCartItemInput, forward them in
buildAddLineItemBySkuIdInput with length/HTTPS/count validation, and
select metafields in getCartOrderQuery so they round-trip on read.
- cart/[id]/items/POST.ts: forward the full validated body instead of a
hand-picked three-field literal.
- cart-model.ts: widen the storefront-side AddToCartItemInput identically.
- commerce-provider.tsx: addItem() was rebuilding a narrowed
{ skuId, name, quantity } object before calling addToCart(), dropping
details/metafields even after the type widened; pass the full item
through instead.
🦋 Changeset detectedLatest commit: b014094 The changes in this PR will be included in the next version bump. This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
Thanks Drew, this is a nice, small change and the contract matches order-api's Worth fixing
Smaller items
What I checked
Could you also add screenshot proof from the MCP playground showing a customized item in hosted checkout (the add-on text and the preview image)? Thanks! |
@sbolinger-godaddy Here's a short Loom showing the line item data before and after: https://www.loom.com/share/0e97ef9539b4401bb1290b648785bd0c I'll get you a catalog add-to-cart view version of this and report back. Edit: Here's another short loom showing the product detail and image (the mug): https://www.loom.com/share/2a72b573652f457b9f5442df1051cfa9 Let me know if you had something else in mind. |
The cart drawer mapped only catalog selectedOptions (Color, Size) into CartItemOptions, so a line's selectedAddons (shopper customization) showed the preview image but not the add-on text, leaving the drawer out of sync with checkout. Fold selectedAddons into the same options list useCart() already exposes, reusing the existing "Label: value" rendering.
… cart
assertValidCartItemInput ran inside buildAddLineItemBySkuIdInput, which on
POST /cart is only reached after addDraftOrder already created the cart —
an invalid productAssetUrl or an oversized add-on list orphaned that cart
and, since it threw a plain Error, came back as a 500 instead of a 400.
Run the same validation in the pre-create loop, and switch every check to
InvalidRequestError so it maps to 400.
Also reject a LIST-option addon value ({ optionValueId }) explicitly: only
TEXT/NUMBER options ({ inputValue }) are supported by this change, and an
optionValueId-only value previously crashed with a TypeError on
.inputValue.length instead of a clean validation error.
Correct a comment that called this guard UX-only with order-api's schema
as the authoritative enforcement point — order-api's schema has no such
length/HTTPS/count limits, so this is the only place they're enforced.
|
@sbolinger-godaddy I believe I've addressed all of your feedback in 454ab95 and b014094. |
pbennett1-godaddy
left a comment
There was a problem hiding this comment.
Reviewed against order-api main (5b1ef214): storefront.graphql and actions/line-items/createFromSkuId.ts. The input shapes (AddLineItemDetailsInput, AddLineItemSelectedAddonsInput, OrderMetafieldInput) and the line-item metafields selection match the storefront subgraph.
Main concerns:
- Same-SKU adds that differ only by metafields/asset URL merge in order-api, and the second add's customization overwrites the first's.
- order-api's
BAD_USER_INPUTvalidation errors (catalog min/max etc.) surface as 502 rather than 400. - Local validation doesn't check runtime types, so malformed bodies 500.
Also not updated: packages/commerce-storefront/docs/server-api.md should document the new details/metafields request fields and the metafields in cart responses. LIST-option (optionValueId) support is fine to defer, since order-api already supports it; maybe track a follow-up.
| quantity: body.quantity, | ||
| }), | ||
| }, | ||
| variables: { input: buildAddLineItemBySkuIdInput(cartId, body as AddToCartItemInput) }, |
There was a problem hiding this comment.
Customized lines can merge and lose the first customization (order-api behavior). order-api's findMatchingLineItem only treats an add as a new line when selectedAddons is present; otherwise it merges into the existing addon-less line with the same skuId, ignoring metafields and productAssetUrl. buildLineItemFromSku then spreads the stored line and overwrites details/metafields with the new add's values.
So adding the same mug with metafields: [{ key: 'designId', value: 'A' }] and then designId: 'B' gives one line, quantity 2, with only design B. That's exactly the metafields-without-addons case in this PR's tests. Either order-api needs to match on metafields/asset URL too, or this contract should document that metafield-only customization isn't line-distinct.
| quantity: body.quantity, | ||
| }), | ||
| }, | ||
| variables: { input: buildAddLineItemBySkuIdInput(cartId, body as AddToCartItemInput) }, |
There was a problem hiding this comment.
Upstream validation failures will reach shoppers as 502. order-api reports its own validation failures as BAD_USER_INPUT (strict-object rejection, catalog option min/max, TEXT/NUMBER single-value rule). The browser can't know catalog min/max, so e.g. a too-short engraving becomes a generic upstream_error 502. Consider a rule in classifyCartUpstreamError (and an equivalent for cart create) mapping BAD_USER_INPUT from addLineItemBySkuId to a 400, with a test.
Note some order-api failures are plain Errors ("Option … does not exist in Catalog", "TEXT or NUMBER option … does not have an inputValue"), which surface as masked INTERNAL_SERVER_ERROR; those need an ActionValidationError fix on the order-api side.
| quantity: body.quantity, | ||
| }), | ||
| }, | ||
| variables: { input: buildAddLineItemBySkuIdInput(cartId, body as AddToCartItemInput) }, |
There was a problem hiding this comment.
body as AddToCartItemInput replaces the field allowlist. Extra client properties now go upstream. order-api's strict schemas will reject them rather than store them, but the shopper gets a 502 instead of a 400. A single parseCartItemInput(body) that returns an allowlisted, runtime-validated item would replace this cast and the double assert in cart/POST.ts.
| throw new InvalidRequestError(`selectedAddons cannot exceed ${MAX_SELECTED_ADDONS} entries`); | ||
| } | ||
| for (const addon of addons) { | ||
| for (const value of addon.values) { |
There was a problem hiding this comment.
Malformed shapes throw TypeErrors → 500. Nothing checks runtime types before iterating: selectedAddons: [{ optionId: 'x' }] (no values), values: [null], a non-array selectedAddons, or metafields: [null] all throw here and land in the generic 500 path instead of InvalidRequestError. Worth checking Array.isArray / typeof === 'string' for each field (and adding tests for these).
| throw new InvalidRequestError(`metafields cannot exceed ${MAX_METAFIELDS} entries`); | ||
| } | ||
| for (const metafield of metafields) { | ||
| if (metafield.value.length > METAFIELD_VALUE_MAX_LENGTH) { |
There was a problem hiding this comment.
metafield.value.length assumes a string: value: 42 gives undefined > 2000 → passes. key isn't checked at all (type or length). Suggest validating both as strings with length caps; order-api has no caps on either.
| } catch { | ||
| throw new InvalidRequestError('productAssetUrl must be an absolute URL'); | ||
| } | ||
| if (parsed.protocol !== 'https:') throw new InvalidRequestError('productAssetUrl must use https'); |
There was a problem hiding this comment.
order-api uses data.details?.productAssetUrl || <catalog media>, so any https URL a shopper sends replaces the catalog image on the merchant's order, emails and fulfillment views. If this is meant for design previews, consider restricting it to a host-configured origin allowlist rather than any https URL.
| author | ||
| authorType | ||
| } | ||
| metafields { |
There was a problem hiding this comment.
Cart reads now return every line-item metafield to the browser, including ones written by the merchant or other apps. Anyone holding a cart id can read them. Consider whether this response should only include keys the storefront wrote, or drop metafields from the browser-facing cart shape.
| 'Each lineItem must have skuId, a non-empty name, and a numeric quantity', | ||
| ); | ||
| } | ||
| assertValidCartItemInput(item); |
There was a problem hiding this comment.
Each item is validated here and again inside buildAddLineItemBySkuIdInput, and the comment has to keep the two in sync. A parse step that returns a sanitized item (see the comment on items/POST.ts) would make this a single call.
| { skuId: item.skuId, name: item.name, quantity: item.quantity }, | ||
| fetchCart, | ||
| ); | ||
| const result: CartResponse = await addToCart(id.current, item, fetchCart); |
There was a problem hiding this comment.
addItem now forwards the caller's whole object, so addItem({ ...product, skuId, name, quantity }) serializes every product property into the POST body (which order-api will then reject as unknown fields → 502). Suggest picking skuId, name, quantity, details, metafields explicitly as before.
| })), | ||
| ...(item.details?.selectedAddons ?? []).map((addon) => ({ | ||
| attribute: addon.attribute ?? '', | ||
| values: (addon.values ?? []).map((value) => value.name ?? ''), |
There was a problem hiding this comment.
value.name ?? '' renders a blank option (e.g. Engraving: ) when a name is missing, and costAdjustment is dropped, so priced addons don't show their surcharge next to a subtotal that includes it.
Summary
Add-to-cart calls can now carry an optional
detailsobject (a product asset URL and selected add-ons) andmetafieldsalongside the existingskuId/name/quantityfields, so a shopper's product customization travels with the line item all the way through checkout instead of being limited to the client. Existing add-to-cart calls that don't use these fields are unaffected.Changeset
Test Plan
Setup
No special setup required — standard local dev environment.
Steps
Run the following:
pnpm --filter @godaddy/gd-commerce-server testdetails/metafieldsreach theaddLineItemBySkuIdmutation and that an invalidproductAssetUrlor an oversized add-on list is rejectedRun the following:
addItem()call forwardsdetails/metafieldsunchanged in the cart POST bodyNote:
colors.test.tsandartifacts.test.tscurrently fail locally withlocalStorage.clear is not a function— this is a pre-existing environment issue unrelated to this change (reproduces identically onmain) and does not affect the 179 other tests, including the new one above.Confirm CI checks pass