Skip to content

Commit

Permalink
building the remove item service for the cart modal
Browse files Browse the repository at this point in the history
  • Loading branch information
AnselmMarie committed Sep 8, 2024
1 parent 71a69df commit e2e7d05
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 70 deletions.
33 changes: 10 additions & 23 deletions apps/api/src/api/v1/cart/controllers/cart.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import {
errFormatResponseUtil,
} from '../../../../utils/err.format.response.util';
import { CartParamsProps } from '../interface/cart.interface';
import { clearCartService, getCartService, updateCartItemService } from '../services/cart.service';
import {
getCartService,
deleteCartItemService,
updateCartItemService,
} from '../services/cart.service';

const getCartController = async (req: Request<null, null, null, null>, res: Response) => {
try {
Expand Down Expand Up @@ -40,38 +44,21 @@ const updateCartItemController = async (
}
};

const removeCartItemController = async (
const deleteCartItemController = async (
req: Request<CartParamsProps, null, null, null>,
res: Response
) => {
const { body } = req;
const { params } = req;

try {
const pokemonRemoved = await updateCartItemService(body).catch(() => {
await deleteCartItemService(params?.id).catch(() => {
throw errFormat500ResponseUtil();
});

res.status(200).json(pokemonRemoved);
res.status(204).json();
} catch (err) {
res.status(err?.status).json(errFormatResponseUtil(err));
}
};

const clearCartController = async (req: Request<null, null, null, null>, res: Response) => {
try {
const pokemonDetail = await clearCartService().catch(() => {
throw errFormat500ResponseUtil();
});

res.status(200).json(pokemonDetail);
} catch (err) {
res.status(err?.status).json(errFormatResponseUtil(err));
}
};

export {
getCartController,
updateCartItemController,
removeCartItemController,
clearCartController,
};
export { getCartController, updateCartItemController, deleteCartItemController };
12 changes: 0 additions & 12 deletions apps/api/src/api/v1/cart/database/cart.database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,3 @@ export const updateCartDataCall = async (data): Promise<CartDataApi> => {
}, 500);
});
};

export const clearCartDataCall = async (): Promise<CartDataApi> => {
return new Promise((resolve) => {
setTimeout(() => {
const data = { data: [], total: 0, counter: 0 };
cartDatabase.data = data.data;
cartDatabase.total = data.total;
cartDatabase.counter = data.counter;
resolve(data);
}, 500);
});
};
8 changes: 3 additions & 5 deletions apps/api/src/api/v1/cart/routes/cart.route.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import express from 'express';

import {
clearCartController,
getCartController,
removeCartItemController,
deleteCartItemController,
updateCartItemController,
} from '../controllers/cart.controller';

const cartRoute = express.Router();

cartRoute.get('/', getCartController);
cartRoute.put('/update/:id', updateCartItemController);
cartRoute.put('/clear', clearCartController);
cartRoute.delete('/item/:id', removeCartItemController);
cartRoute.put('/item/:id', updateCartItemController);
cartRoute.delete('/item/:id', deleteCartItemController);

export { cartRoute };
43 changes: 33 additions & 10 deletions apps/api/src/api/v1/cart/services/cart.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '../../../../utils/err.format.response.util';
import { getPokemonSpeciesService } from '../../pokemon';
import { getPokemonDetailService } from '../../pokemon/services/pokemon.detail.service';
import { clearCartDataCall, getCartDataCall, updateCartDataCall } from '../database/cart.database';
import { getCartDataCall, updateCartDataCall } from '../database/cart.database';

const doesItemExistKeyFn = (data, id) => {
const cartLength = data.length;
Expand Down Expand Up @@ -81,6 +81,14 @@ const updateCartItemService = async (payload: CartApiPayload) => {
return currentObj;
}

if (payload.removeFromCart) {
throw errFormatResponseUtil({
status: 400,
statusText: `This action can't be completed with this endpoint.`,
message: 'We cannot complete this cart action at this moment.',
});
}

const additionalData = await getSpeciesDetail(payload?.id).catch(() => {
throw errFormat500ResponseUtil();
});
Expand All @@ -106,18 +114,33 @@ const updateCartItemService = async (payload: CartApiPayload) => {
return finalPayload;
};

const removeCartItemService = async () => {
const res = await clearCartDataCall().catch(() => {
throw errFormat500ResponseUtil();
const deleteCartItemService = async (id: string) => {
const currentCartData: CartDataApi = clone(
await getCartDataCall().catch(() => {
throw errFormat500ResponseUtil();
})
);
const data = clone(currentCartData.data);
let key = null;
const dataToRemove: any = data.filter((data, i: number) => {
if (data?.id == id) {
key = i;
return data;
}
});
return res;
};
const totalPrice = dataToRemove[0]?.quantity * dataToRemove[0]?.price;

currentCartData.counter = currentCartData.counter - dataToRemove[0]?.quantity;
currentCartData.total = currentCartData.total - totalPrice;

data.splice(key, 1);
currentCartData.data = data;

const clearCartService = async () => {
const res = await clearCartDataCall().catch(() => {
await updateCartDataCall(currentCartData).catch(() => {
throw errFormat500ResponseUtil();
});
return res;

return;
};

export { getCartService, updateCartItemService, removeCartItemService, clearCartService };
export { getCartService, updateCartItemService, deleteCartItemService };
8 changes: 6 additions & 2 deletions libs/features/src/lib/cart/cart.modal/cart.modal.view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import styles from './cart.modal.module.css';
import useCartModalLogic from './use.cart.modal.logic';

const CartModal = (): ReactElement => {
const { data, onHandleRemoveFromCart, onHandleAddToCart } = useCartModalLogic();
const { data, onHandleRemoveFromCart, onHandleAddToCart, onHandleRemoveCartItem } =
useCartModalLogic();

return (
<UiElementLayout className={styles.modal}>
Expand Down Expand Up @@ -53,7 +54,10 @@ const CartModal = (): ReactElement => {
</UiElementLayout>
</UiElementLayout>

<UiIcon icon={IconTypeEnum.ICON_TRASH} />
<UiIcon
icon={IconTypeEnum.ICON_TRASH}
onClick={() => onHandleRemoveCartItem(el?.id)}
/>
</UiElementLayout>

<UiElementLayout className={styles?.sep} />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import { useGetCart, useUpdateCart } from '@pokemon-pet-shop/services';
import { useGetCart, useDeleteCartItem, useUpdateCart } from '@pokemon-pet-shop/services';
import { CartDataApi, GenericNonReturnType } from '@pokemon-pet-shop/typing';

interface UseCartModalReturn {
data: CartDataApi;
onHandleRemoveFromCart: GenericNonReturnType;
onHandleAddToCart: GenericNonReturnType;
onHandleRemoveCartItem: GenericNonReturnType;
}

const useCartModalLogic = (): UseCartModalReturn => {
const { data } = useGetCart();
const updateCartMutation = useUpdateCart();
const deleteCartMutation = useDeleteCartItem();

const handleRemoveCartItem = (id: string) => {
deleteCartMutation.mutate(id);
};

const handleAddToCart = (id: string) => {
updateCartMutation.mutate({
Expand All @@ -31,6 +37,7 @@ const useCartModalLogic = (): UseCartModalReturn => {
data,
onHandleRemoveFromCart: handleRemoveFromCart,
onHandleAddToCart: handleAddToCart,
onHandleRemoveCartItem: handleRemoveCartItem,
};
};

Expand Down
4 changes: 2 additions & 2 deletions libs/services/src/lib/cart/api.cart.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ export const getCart = async () => {
};

export const updateCart = async (data: any) => {
return (await axiosInstance.put<any>(`cart/update/${data?.id}`, data)).data;
return (await axiosInstance.put<any>(`cart/item/${data?.id}`, data)).data;
};

export const clearCart = async () => {
return (await axiosInstance.put<any>('cart/clear')).data;
};

export const deleteCartItem = async (id: number) => {
export const deleteCartItem = async (id: string) => {
return (await axiosInstance.delete<any>(`cart/item/${id}`)).data;
};
17 changes: 2 additions & 15 deletions libs/services/src/lib/cart/cart.mutate.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';

import { clearCart, deleteCartItem, updateCart } from './api.cart.service';
import { deleteCartItem, updateCart } from './api.cart.service';

export function useUpdateCart() {
const queryClient = useQueryClient();
Expand All @@ -19,20 +19,7 @@ export function useDeleteCartItem() {
const queryClient = useQueryClient();

return useMutation({
mutationFn: (id: number) => deleteCartItem(id),
onSettled: async (_, error) => {
if (!error) {
await queryClient.invalidateQueries({ queryKey: ['cart'] });
}
},
});
}

export function useClearCart() {
const queryClient = useQueryClient();

return useMutation({
mutationFn: () => clearCart(),
mutationFn: (id: string) => deleteCartItem(id),
onSettled: async (_, error) => {
if (!error) {
await queryClient.invalidateQueries({ queryKey: ['cart'] });
Expand Down

0 comments on commit e2e7d05

Please sign in to comment.