Skip to main content
Skip to main content

CartService

Constructors

constructor

**new CartService**(«destructured»)

Parameters

__namedParametersInjectedDependenciesRequired

Properties

__configModule__Record<string, unknown>
__container__anyRequired
__moduleDeclaration__Record<string, unknown>
addressRepository_Repository<Address>Required
cartRepository_Repository<Cart> & &#123; findOneWithRelations: Method findOneWithRelations ; findWithRelations: Method findWithRelations &#125;Required
customShippingOptionService_CustomShippingOptionServiceRequired
customerService_CustomerServiceRequired
discountService_DiscountServiceRequired
eventBus_EventBusServiceRequired
featureFlagRouter_FlagRouterRequired
giftCardService_GiftCardServiceRequired
lineItemAdjustmentService_LineItemAdjustmentServiceRequired
lineItemRepository_Repository<LineItem> & &#123; findByReturn: Method findByReturn &#125;Required
lineItemService_LineItemServiceRequired
manager_EntityManagerRequired
newTotalsService_NewTotalsServiceRequired
paymentProviderService_PaymentProviderServiceRequired
paymentSessionRepository_Repository<PaymentSession>Required
priceSelectionStrategy_IPriceSelectionStrategyRequired
pricingService_PricingServiceRequired
productService_ProductServiceRequired
productVariantInventoryService_ProductVariantInventoryServiceRequired
productVariantService_ProductVariantServiceRequired
regionService_RegionServiceRequired
salesChannelService_SalesChannelServiceRequired
shippingMethodRepository_Repository<ShippingMethod>Required
shippingOptionService_ShippingOptionServiceRequired
shippingProfileService_ShippingProfileServiceRequired
storeService_StoreServiceRequired
taxProviderService_TaxProviderServiceRequired
totalsService_TotalsServiceRequired
transactionManager_undefined | EntityManagerRequired
EventsobjectRequired
Events.CREATEDstringRequired

Default: "cart.created"

Events.CUSTOMER_UPDATEDstringRequired

Default: "cart.customer_updated"

Events.UPDATEDstringRequired

Default: "cart.updated"

Accessors

activeManager_

Protected get**activeManager_**(): EntityManager

Returns

EntityManager

EntityManagerEntityManagerRequired

Methods

addLineItem

**addLineItem**(cartId, lineItem, config?): Promise&#60;void&#62;

Adds a line item to the cart.

Parameters

cartIdstringRequired
the id of the cart that we will add to
lineItemLineItemRequired
the line item to add.
configobjectRequired
validateSalesChannels - should check if product belongs to the same sales channel as cart (if cart has associated sales channel)
config.validateSalesChannelsbooleanRequired

Default: true

Returns

Promise<void>

PromisePromise<void>Required
the result of the update operation

Deprecated

Use addOrUpdateLineItems instead.


addOrUpdateLineItems

**addOrUpdateLineItems**(cartId, lineItems, config?): Promise&#60;void&#62;

Adds or update one or multiple line items to the cart. It also update all existing items in the cart to have has_shipping to false. Finally, the adjustments will be updated.

Parameters

cartIdstringRequired
the id of the cart that we will add to
lineItemsLineItem | LineItem[]Required
the line items to add.
configobjectRequired
validateSalesChannels - should check if product belongs to the same sales channel as cart (if cart has associated sales channel)
config.validateSalesChannelsbooleanRequired

Default: true

Returns

Promise<void>

PromisePromise<void>Required
the result of the update operation

addShippingMethod

**addShippingMethod**(cartOrId, optionId, data?): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Adds the shipping method to the list of shipping methods associated with the cart. Shipping Methods are the ways that an order is shipped, whereas a Shipping Option is a possible way to ship an order. Shipping Methods may also have additional details in the data field such as an id for a package shop.

Parameters

cartOrIdstring | CartRequired
the id of the cart to add shipping method to
optionIdstringRequired
id of shipping option to add as valid method
dataRecord<string, unknown>Required
the fulmillment data for the method

Default: {}

Returns

Promise<Cart>

PromisePromise<Cart>Required
the result of the update operation

adjustFreeShipping_

Protected **adjustFreeShipping_**(cart, shouldAdd): Promise&#60;void&#62;

Ensures shipping total on cart is correct in regards to a potential free shipping discount If a free shipping is present, we set shipping methods price to 0 if a free shipping was present, we set shipping methods to original amount

Parameters

cartCartRequired
the cart to adjust free shipping for
shouldAddbooleanRequired
flag to indicate, if we should add or remove

Returns

Promise<void>

PromisePromise<void>Required
void

applyDiscount

**applyDiscount**(cart, discountCode): Promise&#60;void&#62;

Updates the cart's discounts. If discount besides free shipping is already applied, this will be overwritten Throws if discount regions does not include the cart region

Parameters

cartCartRequired
the cart to update
discountCodestringRequired
the discount code

Returns

Promise<void>

PromisePromise<void>Required

applyDiscounts

**applyDiscounts**(cart, discountCodes): Promise&#60;void&#62;

Updates the cart's discounts. If discount besides free shipping is already applied, this will be overwritten Throws if discount regions does not include the cart region

Parameters

cartCartRequired
the cart to update
discountCodesstring[]Required
the discount code(s) to apply

Returns

Promise<void>

PromisePromise<void>Required

applyGiftCard_

Protected **applyGiftCard_**(cart, code): Promise&#60;void&#62;

Parameters

cartCartRequired
A cart represents a virtual shopping bag. It can be used to complete an order, a swap, or a claim.
codestringRequired

Returns

Promise<void>

PromisePromise<void>Required

atomicPhase_

Protected **atomicPhase_**<TypeParameter TResult, TypeParameter TError>(work, isolationOrErrorHandler?, maybeErrorHandlerOrDontFail?): Promise&#60;TResult&#62;

Wraps some work within a transactional block. If the service already has a transaction manager attached this will be reused, otherwise a new transaction manager is created.

TResultobjectRequired
TErrorobjectRequired

Parameters

work(transactionManager: EntityManager) => Promise<TResult>Required
the transactional work to be done
isolationOrErrorHandlerIsolationLevel | (error: TError) => Promise<void | TResult>
the isolation level to be used for the work.
maybeErrorHandlerOrDontFail(error: TError) => Promise<void | TResult>
Potential error handler

Returns

Promise<TResult>

PromisePromise<TResult>Required
the result of the transactional work

authorizePayment

**authorizePayment**(cartId, context?): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Authorizes a payment for a cart. Will authorize with chosen payment provider. This will return a payment object, that we will use to update our cart payment with. Additionally, if the payment does not require more or fails, we will set the payment on the cart.

Parameters

cartIdstringRequired
the id of the cart to authorize payment for
contextRecord<string, unknown> & &#123; cart_id: string &#125;Required
object containing whatever is relevant for authorizing the payment with the payment provider. As an example, this could be IP address or similar for fraud handling.

Returns

Promise<Cart>

PromisePromise<Cart>Required
the resulting cart

create

**create**(data): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Creates a cart.

Parameters

dataCartCreatePropsRequired
the data to create the cart with

Returns

Promise<Cart>

PromisePromise<Cart>Required
the result of the create operation

createOrFetchGuestCustomerFromEmail_

Protected **createOrFetchGuestCustomerFromEmail_**(email): Promise&#60;[Customer](/references/services/classes/Customer)&#62;

Creates or fetches a user based on an email.

Parameters

emailstringRequired
the email to use

Returns

Promise<Customer>

PromisePromise<Customer>Required
the resultign customer object

createTaxLines

**createTaxLines**(cartOrId): Promise&#60;void&#62;

Parameters

cartOrIdstring | CartRequired

Returns

Promise<void>

PromisePromise<void>Required

decorateTotals

**decorateTotals**(cart, totalsConfig?): Promise&#60;[WithRequiredProperty](/references/services/types/WithRequiredProperty)&#60;[Cart](/references/services/classes/Cart), "total"&#62;&#62;

Parameters

cartCartRequired
A cart represents a virtual shopping bag. It can be used to complete an order, a swap, or a claim.
totalsConfigTotalsConfigRequired

Default: {}

Returns

Promise<WithRequiredProperty<Cart, "total">>

PromisePromise<WithRequiredProperty<Cart, "total">>Required

decorateTotals_

Protected **decorateTotals_**(cart, totalsToSelect, options?): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Parameters

cartCartRequired
totalsToSelectTotalField[]Required
optionsTotalsConfigRequired

Returns

Promise<Cart>

PromisePromise<Cart>Required

Deprecated

Use decorateTotals instead


delete

**delete**(cartId): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Deletes a cart from the database. Completed carts cannot be deleted.

Parameters

cartIdstringRequired
the id of the cart to delete

Returns

Promise<Cart>

PromisePromise<Cart>Required
the deleted cart or undefined if the cart was not found.

deletePaymentSession

**deletePaymentSession**(cartId, providerId): Promise&#60;void&#62;

Removes a payment session from the cart.

Parameters

cartIdstringRequired
the id of the cart to remove from
providerIdstringRequired
the id of the provider whose payment session should be removed.

Returns

Promise<void>

PromisePromise<void>Required
the resulting cart.

deleteTaxLines

**deleteTaxLines**(id): Promise&#60;void&#62;

Parameters

idstringRequired

Returns

Promise<void>

PromisePromise<void>Required

findCustomShippingOption

**findCustomShippingOption**(cartCustomShippingOptions, optionId): undefined \| [CustomShippingOption](/references/services/classes/CustomShippingOption)

Finds the cart's custom shipping options based on the passed option id. throws if custom options is not empty and no shipping option corresponds to optionId

Parameters

cartCustomShippingOptionsCustomShippingOption[]Required
the cart's custom shipping options
optionIdstringRequired
id of the normal or custom shipping option to find in the cartCustomShippingOptions

Returns

undefined | CustomShippingOption

undefined \| CustomShippingOptionundefined | CustomShippingOption
custom shipping option

getTotalsRelations

Private **getTotalsRelations**(config): string[]

Parameters

configFindConfig<Cart>Required

Returns

string[]

string[]string[]Required

getValidatedSalesChannel

Protected **getValidatedSalesChannel**(salesChannelId?): Promise&#60;[SalesChannel](/references/services/classes/SalesChannel)&#62;

Parameters

salesChannelIdstring

Returns

Promise<SalesChannel>

PromisePromise<SalesChannel>Required

list

**list**(selector, config?): Promise&#60;[Cart](/references/services/classes/Cart)[]&#62;

Parameters

selectorFilterableCartPropsRequired
the query object for find
configFindConfig<Cart>Required
config object

Default: {}

Returns

Promise<Cart[]>

PromisePromise<Cart[]>Required
the result of the find operation

onSalesChannelChange

Protected **onSalesChannelChange**(cart, newSalesChannelId): Promise&#60;void&#62;

Remove the cart line item that does not belongs to the newly assigned sales channel

Parameters

cartCartRequired
The cart being updated
newSalesChannelIdstringRequired
The new sales channel being assigned to the cart

Returns

Promise<void>

PromisePromise<void>Required
void

refreshAdjustments_

Protected **refreshAdjustments_**(cart): Promise&#60;void&#62;

Parameters

cartCartRequired
A cart represents a virtual shopping bag. It can be used to complete an order, a swap, or a claim.

Returns

Promise<void>

PromisePromise<void>Required

refreshPaymentSession

**refreshPaymentSession**(cartId, providerId): Promise&#60;void&#62;

Refreshes a payment session on a cart

Parameters

cartIdstringRequired
the id of the cart to remove from
providerIdstringRequired
the id of the provider whose payment session should be removed.

Returns

Promise<void>

PromisePromise<void>Required
the resulting cart.

removeDiscount

**removeDiscount**(cartId, discountCode): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Removes a discount based on a discount code.

Parameters

cartIdstringRequired
the id of the cart to remove from
discountCodestringRequired
the discount code to remove

Returns

Promise<Cart>

PromisePromise<Cart>Required
the resulting cart

removeLineItem

**removeLineItem**(cartId, lineItemId): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Removes a line item from the cart.

Parameters

cartIdstringRequired
the id of the cart that we will remove from
lineItemIdstringRequired
the line item to remove.

Returns

Promise<Cart>

PromisePromise<Cart>Required
the result of the update operation

retrieve

**retrieve**(cartId, options?, totalsConfig?): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Gets a cart by id.

Parameters

cartIdstringRequired
the id of the cart to get.
optionsFindConfig<Cart>Required
the options to get a cart

Default: {}

totalsConfigTotalsConfigRequired

Default: {}

Returns

Promise<Cart>

PromisePromise<Cart>Required
the cart document.

retrieveLegacy

Protected **retrieveLegacy**(cartId, options?, totalsConfig?): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Parameters

cartIdstringRequired
optionsFindConfig<Cart>Required

Default: {}

totalsConfigTotalsConfigRequired

Default: {}

Returns

Promise<Cart>

PromisePromise<Cart>Required

Deprecated


retrieveWithTotals

**retrieveWithTotals**(cartId, options?, totalsConfig?): Promise&#60;[WithRequiredProperty](/references/services/types/WithRequiredProperty)&#60;[Cart](/references/services/classes/Cart), "total"&#62;&#62;

Parameters

cartIdstringRequired
optionsFindConfig<Cart>Required

Default: {}

totalsConfigTotalsConfigRequired

Default: {}

Returns

Promise<WithRequiredProperty<Cart, "total">>

PromisePromise<WithRequiredProperty<Cart, "total">>Required

setMetadata

**setMetadata**(cartId, key, value): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Dedicated method to set metadata for a cart. To ensure that plugins does not overwrite each others metadata fields, setMetadata is provided.

Parameters

cartIdstringRequired
the cart to apply metadata to.
keystringRequired
key for metadata field
valuestring | numberRequired
value for metadata field.

Returns

Promise<Cart>

PromisePromise<Cart>Required
resolves to the updated result.

setPaymentSession

**setPaymentSession**(cartId, providerId): Promise&#60;void&#62;

Selects a payment session for a cart and creates a payment object in the external provider system

Parameters

cartIdstringRequired
the id of the cart to add payment method to
providerIdstringRequired
the id of the provider to be set to the cart

Returns

Promise<void>

PromisePromise<void>Required

setPaymentSessions

**setPaymentSessions**(cartOrCartId): Promise&#60;void&#62;

Creates, updates and sets payment sessions associated with the cart. The first time the method is called payment sessions will be created for each provider. Additional calls will ensure that payment sessions have correct amounts, currencies, etc. as well as make sure to filter payment sessions that are not available for the cart's region.

Parameters

cartOrCartIdstring | CartRequired
the id of the cart to set payment session for

Returns

Promise<void>

PromisePromise<void>Required
the result of the update operation.

setRegion_

Protected **setRegion_**(cart, regionId, countryCode): Promise&#60;void&#62;

Set's the region of a cart.

Parameters

cartCartRequired
the cart to set region on
regionIdstringRequired
the id of the region to set the region to
countryCodenull | stringRequired
the country code to set the country to

Returns

Promise<void>

PromisePromise<void>Required
the result of the update operation

shouldRetryTransaction_

Protected **shouldRetryTransaction_**(err): boolean

Parameters

errRecord<string, unknown> | &#123; code: string &#125;Required

Returns

boolean

booleanboolean

transformQueryForTotals_

Protected **transformQueryForTotals_**(config): [FindConfig](/references/services/interfaces/FindConfig)&#60;[Cart](/references/services/classes/Cart)&#62; & &#123; totalsToSelect: [TotalField](/references/services/types/TotalField)[] &#125;

Parameters

configFindConfig<Cart>Required

Returns

FindConfig<Cart> & &#123; totalsToSelect: [TotalField](/references/services/types/TotalField)[] &#125;

FindConfig&#60;Cart&#62; & &#123; totalsToSelect: TotalField[] &#125;FindConfig<Cart> & &#123; totalsToSelect: [TotalField](/references/services/types/TotalField)[] &#125;

update

**update**(cartOrId, data): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Parameters

cartOrIdstring | CartRequired
dataCartUpdatePropsRequired

Returns

Promise<Cart>

PromisePromise<Cart>Required

updateBillingAddress_

Protected **updateBillingAddress_**(cart, addressOrId, addrRepo): Promise&#60;void&#62;

Updates the cart's billing address.

Parameters

cartCartRequired
the cart to update
addressOrIdstring | AddressPayload | Partial<Address>Required
the value to set the billing address to
addrRepoRepository<Address>Required
the repository to use for address updates

Returns

Promise<void>

PromisePromise<void>Required
the result of the update operation

updateCustomerId_

Protected **updateCustomerId_**(cart, customerId): Promise&#60;void&#62;

Sets the customer id of a cart

Parameters

cartCartRequired
the cart to add email to
customerIdstringRequired
the customer to add to cart

Returns

Promise<void>

PromisePromise<void>Required
the result of the update operation

updateLineItem

**updateLineItem**(cartId, lineItemId, update): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Updates a cart's existing line item.

Parameters

cartIdstringRequired
the id of the cart to update
lineItemIdstringRequired
the id of the line item to update.
updateLineItemUpdateRequired

Returns

Promise<Cart>

PromisePromise<Cart>Required
the result of the update operation

updatePaymentSession

**updatePaymentSession**(cartId, update): Promise&#60;[Cart](/references/services/classes/Cart)&#62;

Updates the currently selected payment session.

Parameters

cartIdstringRequired
the id of the cart to update the payment session for
updateRecord<string, unknown>Required
the data to update the payment session with

Returns

Promise<Cart>

PromisePromise<Cart>Required
the resulting cart

updateShippingAddress_

Protected **updateShippingAddress_**(cart, addressOrId, addrRepo): Promise&#60;void&#62;

Updates the cart's shipping address.

Parameters

cartCartRequired
the cart to update
addressOrIdstring | AddressPayload | Partial<Address>Required
the value to set the shipping address to
addrRepoRepository<Address>Required
the repository to use for address updates

Returns

Promise<void>

PromisePromise<void>Required
the result of the update operation

updateUnitPrices_

Protected **updateUnitPrices_**(cart, regionId?, customer_id?): Promise&#60;void&#62;

Parameters

cartCartRequired
A cart represents a virtual shopping bag. It can be used to complete an order, a swap, or a claim.
regionIdstring
customer_idstring

Returns

Promise<void>

PromisePromise<void>Required

validateLineItem

Protected **validateLineItem**(sales_channel_id, lineItem): Promise&#60;boolean&#62;

Check if line item's variant belongs to the cart's sales channel.

Parameters

sales_channel_idobjectRequired
the cart for the line item
sales_channel_id.sales_channel_idnull | stringRequired
lineItemLineItemValidateDataRequired
the line item being added

Returns

Promise<boolean>

PromisePromise<boolean>Required
a boolean indicating validation result

validateLineItemShipping_

Protected **validateLineItemShipping_**(shippingMethods, lineItemShippingProfiledId): boolean

Checks if a given line item has a shipping method that can fulfill it. Returns true if all products in the cart can be fulfilled with the current shipping methods.

Parameters

shippingMethodsShippingMethod[]Required
the set of shipping methods to check from
lineItemShippingProfiledIdstringRequired

Returns

boolean

booleanboolean
boolean representing whether shipping method is validated

withTransaction

**withTransaction**(transactionManager?): [CartService](/references/services/classes/CartService)

Parameters

transactionManagerEntityManager

Returns

CartService

CartServiceCartServiceRequired
Was this section helpful?