Alokai

updateCart

Update an existing cart.

It updates a cart in commercetools by sending a request to its GraphQL API. The default GraphQL query used by this method can be found updateCartDefaultQuery.

When the method is called with an incorrect cartVersion and commercetools API responds with the ConcurrentModification error, our Alokai Middleware automatically retries the failed request with the correct version. To disable that behavior, set the versionFallback to false.

This method allows for performing more complex cart updates with multiple update actions at once. For single-action updates, you should use one of the more specific SDK methods such as - addToCart, - removeFromCart, - applyCartCoupon, - removeCartCoupon, - updateCartQuantity, - setDefaultBillingAddress, - setDefaultShippingAddress, - updateShippingDetails.

Signature

declare function updateCart(
	context: CommercetoolsIntegrationContext,
	params: UpdateCartParams,
	customQuery?: CustomQuery
): Promise<UpdateCartResponse>;

Parameters

NameRequiredTypeDescription
contextRequiredCommercetoolsIntegrationContext
paramsRequiredUpdateCartParams
customQueryOptionalCustomQuery

Returns

Returns a representation of the UpdateCartResponse.

Referenced Types

Examples

Updating cart with a single action.

const { cart } = await sdk.commerce.updateCart({
  cartId: '6931b5d2-986f-4d2b-8cba-45007a26eb5e',
  cartVersion: 1,
  actions: [
    { addDiscountCode: { code: 'code' } }
  ]
});

Updating cart with multiple actions.

const { cart } = await sdk.commerce.updateCart({
  cartId: '6931b5d2-986f-4d2b-8cba-45007a26eb5e',
  cartVersion: 1,
  actions: [
    { addDiscountCode: { code: 'code' } },
    { addLineItem: { quantity: 1, sku: 'M0E20000000DHRL' } }
  ]
});

Creating a custom GraphQL query for the method in middleware.config.ts. We can use it to specify response fields as well as overwrite certain query variables.

export const integrations = {
    ct: {
      // ...
      customQueries: {
        'update-cart-custom-query': ({ query, variables, metadata }) => ({
          variables: Object.assign(variables, metadata?.variables),
          query: `
            mutation updateCart(
              $id: String!,
              $version: Long!,
              $actions: [MyCartUpdateAction!]!,
              $storeKey: KeyReferenceInput
            ) {
              cart: updateMyCart(id: $id, version: $version, actions: $actions, storeKey: $storeKey) {
                ${metadata.fields}
              }
            }
          `;
        }
      }
    }
  }
};

Updating cart and selecting response fields using the custom GraphQL query from the previous example.

const customQuery = {
  updateCart: 'update-cart-custom-query',
  metadata: {
    fields: 'id, version'
  }
};

const { cart } = await sdk.commerce.updateCart({
  cartId: '6931b5d2-986f-4d2b-8cba-45007a26eb5e',
  cartVersion: 1,
  actions: [
    { addDiscountCode: { code: 'code' } }
  ]
}, customQuery)

On this page