mergeCartAction.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use server";
  2. import {cookies} from "next/headers";
  3. import { GUEST_CART_ID, GUEST_CART_TOKEN, IS_GUEST } from "@/utils/constants";
  4. import { serverGraphqlFetch } from "@utils/bagisto";
  5. import { CREATE_MERGE_CART } from "@/graphql";
  6. import { CreateMergeCartData } from "@/types/cart/type";
  7. export async function mergeCartAction(){
  8. const cookieStore = await cookies();
  9. const guestCartId = cookieStore.get(GUEST_CART_ID)?.value;
  10. cookieStore.delete(GUEST_CART_ID);
  11. cookieStore.delete(GUEST_CART_TOKEN);
  12. cookieStore.set(IS_GUEST,"false");
  13. if(!guestCartId){
  14. return {
  15. cartDetail: null,
  16. success:true,
  17. msg: ''
  18. };
  19. }
  20. try{
  21. // 调 Bagisto merge cart mutation
  22. const response = await serverGraphqlFetch<CreateMergeCartData,{cartId:number}>({
  23. query: CREATE_MERGE_CART,
  24. variables: {
  25. cartId: Number(guestCartId)
  26. },
  27. cache: "no-store",
  28. });
  29. const cartData = response.data?.createMergeCart?.mergeCart ?? null;
  30. let success = true;
  31. let msg = "";
  32. if(response.error) {
  33. success = false;
  34. msg = response.error.message;
  35. }
  36. return {
  37. cartDetail: cartData,
  38. success: success,
  39. msg: msg
  40. };
  41. } catch(e: any) {
  42. return {
  43. cartDetail: null,
  44. success:false,
  45. msg: e.message || 'Fail to merge cart.'
  46. };
  47. }
  48. }