Skip to content

Commit

Permalink
Icky 177 (vercel#13)
Browse files Browse the repository at this point in the history
* addItemToCart function implemneted

Conflicts resolved

* Add Item to cart functionality implemented

* remove Item from cart implemented

* removed unused code

Co-authored-by: Chandradeepta <43542673+Chandradeepta@users.noreply.github.com>
  • Loading branch information
kibo-chandradeeptalaha and Chandradeepta committed Sep 8, 2021
1 parent c09a1c4 commit af8c7e0
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 13 deletions.
4 changes: 2 additions & 2 deletions framework/kibocommerce/api/endpoints/cart/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import getCart from './get-cart';
import addItem from './add-item';

// import updateItem from './update-item'
// import removeItem from './remove-item'
import removeItem from './remove-item'

export type CartAPI = GetAPISchema<KiboCommerceAPI, any>

Expand All @@ -15,7 +15,7 @@ export const handlers: CartEndpoint['handlers'] = {
getCart,
addItem,
// updateItem,
// removeItem,
removeItem,
}

const cartApi = createEndpoint<CartAPI>({
Expand Down
43 changes: 43 additions & 0 deletions framework/kibocommerce/api/endpoints/cart/remove-item.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { normalizeCart } from '../../../lib/normalize'
// import getCartCookie from '../../utils/get-cart-cookie'
import type { CartEndpoint } from '.'
import removeItemFromCartMutation from '@framework/api/mutations/removeItemFromCart-mutation'
import { getCartQuery } from '@framework/api/queries/getCartQuery'

const removeItem: CartEndpoint['handlers']['removeItem'] = async ({
req,
res,
body: { cartId, itemId },
config,
}) => {
if (!itemId) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
const token = req.cookies[config.customerCookie]

let accessToken = token ? JSON.parse(token).accessToken : null

const removeItemResponse = await config.fetch(
removeItemFromCartMutation,
{
variables: { id: itemId },
},
{ headers: { 'x-vol-user-claims': accessToken } }
)

let currentCart = null
if (removeItemResponse.data.deleteCurrentCartItem) {
let result = await config.fetch(
getCartQuery,
{},
{ headers: { 'x-vol-user-claims': accessToken } }
)
currentCart = result?.data?.currentCart
}
res.status(200).json({ data: normalizeCart(currentCart) })
}

export default removeItem
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* Delete cart based on current user session
*/
const removeItemFromCartMutation = /*GraphQL*/`
mutation deleteCartItem($id: String!) {
deleteCurrentCartItem(cartItemId:$id)
}`;

export default removeItemFromCartMutation;
1 change: 0 additions & 1 deletion framework/kibocommerce/api/utils/fetch-store-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ const fetchStoreApi = <T>(getConfig: () => KiboCommerceConfig) => async (

if (!res.ok) {
const data = isJSON ? await res.json() : await getTextOrNull(res)
console.log('-----------anon-----------', data)
const headers = getRawHeaders(res)
const msg = `Kibo Commerce API error (${
res.status
Expand Down
58 changes: 48 additions & 10 deletions framework/kibocommerce/cart/use-remove-item.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,56 @@
import { MutationHook } from '@commerce/utils/types'
import { useCallback } from 'react'
import type {
MutationHookContext,
HookFetcherContext,
} from '@commerce/utils/types'
import { ValidationError } from '@commerce/utils/errors'
import useRemoveItem, { UseRemoveItem } from '@commerce/cart/use-remove-item'
import type { Cart, LineItem, RemoveItemHook } from '@commerce/types/cart'
import useCart from './use-cart'

export type RemoveItemFn<T = any> = T extends LineItem
? (input?: RemoveItemActionInput<T>) => Promise<Cart | null | undefined>
: (input: RemoveItemActionInput<T>) => Promise<Cart | null>

export type RemoveItemActionInput<T = any> = T extends LineItem
? Partial<RemoveItemHook['actionInput']>
: RemoveItemHook['actionInput']

export default useRemoveItem as UseRemoveItem<typeof handler>

export const handler: MutationHook<any> = {
export const handler = {
fetchOptions: {
query: '',
url: '/api/cart',
method: 'DELETE',
},
async fetcher({ input, options, fetch }) {},
useHook:
({ fetch }) =>
() => {
return async function removeItem(input) {
return {}
async fetcher({
input: { itemId },
options,
fetch,
}: HookFetcherContext<RemoveItemHook>) {
return await fetch({ ...options, body: { itemId } })
},
useHook: ({ fetch }: MutationHookContext<RemoveItemHook>) => <
T extends LineItem | undefined = undefined
>(
ctx: { item?: T } = {}
) => {
const { item } = ctx
const { mutate } = useCart()
const removeItem: RemoveItemFn<LineItem> = async (input) => {
const itemId = input?.id ?? item?.id

if (!itemId) {
throw new ValidationError({
message: 'Invalid input used for this operation',
})
}
},

const data = await fetch({ input: { itemId } })
await mutate(data, false)
return data
}

return useCallback(removeItem as RemoveItemFn<T>, [fetch, mutate])
},
}

0 comments on commit af8c7e0

Please sign in to comment.