Alokai

addProductsToCart

Add products to cart.

Signature

declare function addProductsToCart(
	context: Context,
	input: MutationAddProductsToCartArgs,
	customQuery?: CustomQuery,
	customHeaders?: CustomHeaders
): Promise<FetchResult<AddProductsToCartMutation>>;

Parameters

NameRequiredTypeDescription
contextRequiredContext
inputRequiredMutationAddProductsToCartArgs
customQueryOptionalCustomQuery
customHeadersOptionalCustomHeaders

Referenced Types

Examples

Simple usage:

import { sdk } from '~/sdk.config.ts';

// add products to cart with default parameters (returns cart)
const cart = await sdk.magento.addProductsToCart(
  {
    cartId: '123',
    cartItems: [
      {
        sku: 'WSH12',
        quantity: 1,
        selected_options: [
          // option IDs retrieved from product
          'Y29uZmlndXJhYmxlLzkzLzUz',
          'Y29uZmlndXJhYmxlLzE0NC8xNzE='
        ]
      }
    ]
  }
);

Creating a custom GraphQL query for adding products to cart

module.exports = {
  integrations: {
    magento: {
      customQueries: {
        'add-products-to-cart-custom-query': ({ variables, metadata }) => ({
           variables,
           query: `
             mutation addProductsToCart($cartId: String!, $cartItems: [CartItemInput!]!) {
               addProductsToCart(cartId: $cartId, cartItems: $cartItems) {
                 cart {
                   ${metadata.fields}
                 }
               }
             }`

        }),
      },
    }
  }
};

Using a custom GraphQL query to modify response containing the cart, which is sent as part of the adding product to cart mutation

import { sdk } from '~/sdk.config.ts';
// reduce the amount of fields returned by the query, when compared to the default query
const customQuery = {
  cart: 'add-products-to-cart-custom-query',
  metadata: {
    fields: 'id items { uid }'
  }
};


const cart = await sdk.magento.addProductsToCart(
  {
    cartId: '123',
    cartItems: [
      {
        sku: 'WSH12',
        quantity: 1,
        selected_options: [
          'Y29uZmlndXJhYmxlLzkzLzUz',
          'Y29uZmlndXJhYmxlLzE0NC8xNzE='
        ]
      }
    ]
  },
  customQuery
);

// Result will contain only the fields specified in the custom query.

On this page