logoutAction.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use server";
  2. import {cookies} from "next/headers";
  3. import { IS_GUEST } from "@/utils/constants";
  4. import { serverGraphqlFetch } from "@utils/bagisto";
  5. import {CUSTOMER_LOGOUT} from "@/graphql/customer/mutations";
  6. import type { LogoutData } from "@/types/types";
  7. export async function logoutAction() {
  8. try {
  9. const res = await serverGraphqlFetch<LogoutData>({
  10. query: CUSTOMER_LOGOUT,
  11. });
  12. let success = true;
  13. let msg = "";
  14. if(res.error) {
  15. success = false;
  16. msg = res.error.message;
  17. } else {
  18. success = res.data?.createLogout?.logout?.success ?? false;
  19. msg = res.data?.createLogout?.logout?.message ?? "";
  20. if(success || (!success && msg === "Unauthenticated. Please login to perform this action")) {
  21. const cookieStore = await cookies();
  22. // 设置游客状态
  23. cookieStore.set(IS_GUEST, "true");
  24. success = true;
  25. }
  26. }
  27. return {
  28. success,
  29. message: msg,
  30. };
  31. } catch (error: unknown) {
  32. return {
  33. success: false,
  34. message: error instanceof Error ? error.message : "Something went wrong",
  35. };
  36. }
  37. }