actions.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use server";
  2. // 文件顶部的 "use server" 是所有导出的异步函数自动成为 Server Action 的标志。
  3. import { redirect } from "next/navigation";
  4. import {
  5. subscribeUser,
  6. } from '@/utils/bagisto';
  7. import type { RecoverPasswordFormState } from "@components/customer/types";
  8. export type RegisterFormState = {
  9. errors?: {
  10. firstName?: string[];
  11. lastName?: string[];
  12. email?: string[];
  13. password?: string[];
  14. passwordConfirmation?: string[];
  15. apiError?: string;
  16. agreement?: string[];
  17. };
  18. };
  19. export async function redirectToCheckout(formData: FormData) {
  20. const url = formData.get("url") as string;
  21. redirect(url);
  22. }
  23. export async function userSubscribe(
  24. _prevState: RecoverPasswordFormState,
  25. formData: FormData
  26. ): Promise<RecoverPasswordFormState> {
  27. const email = formData.get("email");
  28. const data = {
  29. email: typeof email === "string" ? email.trim() : "",
  30. };
  31. try {
  32. const result = await subscribeUser(data) as Record<string, unknown>;
  33. if (result?.error) {
  34. const error = result.error as Record<string, unknown>;
  35. return {
  36. errors: {
  37. apiRes: {
  38. status: false,
  39. msg: (error.message as string) || "Something went wrong",
  40. },
  41. },
  42. };
  43. }
  44. const body = result?.body as Record<string, unknown>;
  45. const bodyData = body?.data as Record<string, unknown>;
  46. return {
  47. errors: {
  48. apiRes: {
  49. status: true,
  50. msg: (bodyData?.message as string) || "Subscription successful!",
  51. },
  52. },
  53. };
  54. } catch {
  55. return {
  56. errors: {
  57. apiRes: {
  58. status: false,
  59. msg: "Unexpected error occurred. Please try again.",
  60. },
  61. },
  62. };
  63. }
  64. }