forked from vercel/commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
Add cart hooks #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nicososadevgurus
wants to merge
1
commit into
master
Choose a base branch
from
TEC-259
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { normalizeCart } from '@framework/lib/normalize' | ||
| import getCookie from '@framework/api/utils/get-cookie' | ||
| import type { CartEndpoint } from '.' | ||
| import { createCartMutation } from '@framework/utils/mutations/create-cart-mutation' | ||
| import { updateCartMutation } from '@framework/utils/mutations/update-cart-mutation' | ||
| import { getCartQuery } from '@framework/utils/queries/get-cart-query' | ||
| import type { CommercetoolsCart } from '@framework/types/cart' | ||
|
|
||
| //TODO: Use anonymous session, set customerId on cart and handle currency with locale | ||
| const addItem: CartEndpoint['handlers']['addItem'] = async ({ | ||
| res, | ||
| body: { cartId, item }, | ||
| config, | ||
| }) => { | ||
| if (!item) { | ||
| return res.status(404).json({ | ||
| data: null, | ||
| errors: [{ message: 'Missing item' }], | ||
| }) | ||
| } | ||
|
|
||
| if (!item.quantity) item.quantity = 1 | ||
| const { currency } = config | ||
| let result = null | ||
| if (!cartId) { | ||
| const body = { | ||
| draft: { | ||
| currency: currency, | ||
| lineItems: [ | ||
| { | ||
| productId: item.productId, | ||
| quantity: item.quantity, | ||
| variantId: Number(item.variantId), | ||
| }, | ||
| ], | ||
| }, | ||
| } | ||
| result = (await config.fetch(createCartMutation, { variables: body }))?.data | ||
| ?.createCart | ||
| } else { | ||
| const locale = config.getLocale() | ||
| const variables = { | ||
| id: cartId, | ||
| locale: locale, | ||
| } | ||
| const activeCart: CommercetoolsCart = ( | ||
| await config.fetch(getCartQuery, { variables }) | ||
| )?.data?.cart | ||
|
|
||
| const body = { | ||
| version: activeCart.version, | ||
| id: cartId, | ||
| actions: [ | ||
| { | ||
| addLineItem: { | ||
| productId: item.productId, | ||
| variantId: Number(item.variantId), | ||
| quantity: item.quantity, | ||
| }, | ||
| }, | ||
| ], | ||
| } | ||
|
|
||
| result = (await config.fetch(updateCartMutation, { variables: body }))?.data | ||
| ?.updateCart | ||
| } | ||
| if (result) { | ||
| res.setHeader( | ||
| 'Set-Cookie', | ||
| getCookie(config.cartCookie, result.id, config.cookieMaxAge) | ||
| ) | ||
| res.status(200).json({ data: result && normalizeCart(result) }) | ||
| } | ||
| } | ||
|
|
||
| export default addItem | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { normalizeCart } from '@framework/lib/normalize' | ||
| import { CommercetoolsGraphQLError } from '@framework/api/utils/errors' | ||
| import getCookie from '@framework/api/utils/get-cookie' | ||
| import type { CommercetoolsCart } from '@framework/types/cart' | ||
| import type { CartEndpoint } from '.' | ||
| import { getCartQuery } from '@framework/utils/queries/get-cart-query' | ||
|
|
||
| // Return current cart info | ||
| const getCart: CartEndpoint['handlers']['getCart'] = async ({ | ||
| res, | ||
| body: { cartId }, | ||
| config, | ||
| }) => { | ||
| let result: { data?: { cart: CommercetoolsCart } } = {} | ||
| const locale = config.getLocale() | ||
| if (cartId) { | ||
| try { | ||
| const variables = { | ||
| id: cartId, | ||
| locale: locale, | ||
| } | ||
| result = await config.fetch(getCartQuery, { variables }) | ||
| } catch (error) { | ||
| if (error instanceof CommercetoolsGraphQLError) { | ||
| // Remove the cookie if it exists but the cart wasn't found | ||
| res.setHeader('Set-Cookie', getCookie(config.cartCookie)) | ||
| } else { | ||
| throw error | ||
| } | ||
| } | ||
| } | ||
| let normalizedCart = null | ||
| if (result.data) { | ||
| normalizedCart = normalizeCart(result.data.cart) | ||
| } | ||
|
|
||
| res.status(200).json({ | ||
| data: normalizedCart, | ||
| }) | ||
| } | ||
| export default getCart |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { GetAPISchema, createEndpoint } from '@commerce/api' | ||
| import cartEndpoint from '@commerce/api/endpoints/cart' | ||
| import type { CartSchema } from '../../../types/cart' | ||
| import type { CommercetoolsAPI } from '../..' | ||
| import getCart from './get-cart' | ||
| import addItem from './add-item' | ||
| import updateItem from './update-item' | ||
| import removeItem from './remove-item' | ||
|
|
||
| export type CartAPI = GetAPISchema<CommercetoolsAPI, CartSchema> | ||
|
|
||
| export type CartEndpoint = CartAPI['endpoint'] | ||
|
|
||
| export const handlers: CartEndpoint['handlers'] = { | ||
| getCart, | ||
| addItem, | ||
| updateItem, | ||
| removeItem, | ||
| } | ||
|
|
||
| const cartApi = createEndpoint<CartAPI>({ | ||
| handler: cartEndpoint, | ||
| handlers, | ||
| }) | ||
|
|
||
| export default cartApi |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| import { normalizeCart } from '@framework/lib/normalize' | ||
| import getCookie from '@framework/api/utils/get-cookie' | ||
| import type { CartEndpoint } from '.' | ||
| import { getCartQuery } from '@framework/utils/queries/get-cart-query' | ||
| import { updateCartMutation } from '@framework/utils/mutations/update-cart-mutation' | ||
| import type { CommercetoolsCart } from '@framework/types/cart' | ||
| import findItemQuantity from '@framework/api/utils/find-item-quantity' | ||
|
|
||
| const removeItem: CartEndpoint['handlers']['removeItem'] = async ({ | ||
| res, | ||
| body: { cartId, itemId }, | ||
| config, | ||
| }) => { | ||
| if (!cartId || !itemId) { | ||
| return res.status(404).json({ | ||
| data: null, | ||
| errors: [{ message: 'Invalid request' }], | ||
| }) | ||
| } | ||
| const locale = config.getLocale() | ||
| const variables = { | ||
| id: cartId, | ||
| locale: locale, | ||
| } | ||
| const activeCart: CommercetoolsCart = ( | ||
| await config.fetch(getCartQuery, { variables }) | ||
| )?.data?.cart | ||
| const quantity: number = findItemQuantity(activeCart.lineItems, itemId) | ||
| const body = { | ||
| id: cartId, | ||
| version: activeCart?.version, | ||
| actions: [ | ||
| { | ||
| removeLineItem: { | ||
| lineItemId: itemId, | ||
| quantity: quantity, | ||
| }, | ||
| }, | ||
| ], | ||
| } | ||
| const result: CommercetoolsCart = ( | ||
| await config.fetch(updateCartMutation, { variables: body }) | ||
| )?.data?.updateCart | ||
|
|
||
| res.setHeader( | ||
| 'Set-Cookie', | ||
| result | ||
| ? // Update the cart cookie | ||
| getCookie(config.cartCookie, cartId, config.cookieMaxAge) | ||
| : // Remove the cart cookie if the cart was removed (empty items) | ||
| getCookie(config.cartCookie) | ||
| ) | ||
| res.status(200).json({ data: result ? normalizeCart(result) : null }) | ||
| } | ||
|
|
||
| export default removeItem |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import { normalizeCart } from '@framework/lib/normalize' | ||
| import getCookie from '@framework/api/utils/get-cookie' | ||
| import type { CartEndpoint } from '.' | ||
| import type { CommercetoolsCart } from '@framework/types/cart' | ||
| import { updateCartMutation } from '@framework/utils/mutations/update-cart-mutation' | ||
| import { getCartQuery } from '@framework/utils/queries/get-cart-query' | ||
| import { QUANTITY_TO_UPDATE } from '@framework/consts' | ||
| const updateItem: CartEndpoint['handlers']['updateItem'] = async ({ | ||
| res, | ||
| body: { cartId, itemId, item }, | ||
| config, | ||
| }) => { | ||
| if (!cartId || !itemId || !item) { | ||
| return res.status(400).json({ | ||
| data: null, | ||
| errors: [{ message: 'Invalid request' }], | ||
| }) | ||
| } | ||
| const locale = config.getLocale() | ||
| const variables = { | ||
| id: cartId, | ||
| locale: locale, | ||
| } | ||
| const activeCart: CommercetoolsCart = ( | ||
| await config.fetch(getCartQuery, { variables }) | ||
| )?.data?.cart | ||
| const lineItemToUpdate = activeCart | ||
| ? activeCart.lineItems.find( | ||
| (lineItem) => lineItem.productId === item.productId | ||
| ) | ||
| : null | ||
|
|
||
| const actions = | ||
| lineItemToUpdate && | ||
| lineItemToUpdate.quantity && | ||
| item.quantity && | ||
| lineItemToUpdate.quantity > item.quantity | ||
| ? { | ||
| removeLineItem: { | ||
| lineItemId: itemId, | ||
| quantity: QUANTITY_TO_UPDATE, | ||
| }, | ||
| } | ||
| : { | ||
| addLineItem: { | ||
| productId: item.productId, | ||
| variantId: item.variantId, | ||
| quantity: QUANTITY_TO_UPDATE, | ||
| }, | ||
| } | ||
|
|
||
| const body = { | ||
| version: activeCart.version, | ||
| id: activeCart.id, | ||
| actions: [actions], | ||
| } | ||
| try { | ||
| const result: CommercetoolsCart = ( | ||
| await config.fetch(updateCartMutation, { variables: body }) | ||
| )?.data?.updateCart | ||
| res.setHeader( | ||
| 'Set-Cookie', | ||
| getCookie(config.cartCookie, cartId, config.cookieMaxAge) | ||
| ) | ||
| res.status(200).json({ data: result && normalizeCart(result) }) | ||
| } catch (error) { | ||
| throw Error(`Error updating: ${error}`) | ||
| } | ||
| } | ||
|
|
||
| export default updateItem |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why do you create the cart when no id is there? I mean, is not wrong but just want to know the reasons
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because the cartId comes from the cookies, and if it is not saved in the cookies we assume that there is no cart created