Procházet zdrojové kódy

添加rest api接口地址和rest api 请求方法

fogwind před 1 týdnem
rodič
revize
299944e455
3 změnil soubory, kde provedl 98 přidání a 2 odebrání
  1. 10 1
      src/utils/auth.ts
  2. 86 1
      src/utils/bagisto/index.ts
  3. 2 0
      src/utils/constants.ts

+ 10 - 1
src/utils/auth.ts

@@ -1,6 +1,6 @@
 import NextAuth, { NextAuthOptions } from "next-auth";
 import CredentialsProvider from "next-auth/providers/credentials";
-import { bagistoFetch } from "@/utils/bagisto";
+import { bagistoFetch, restApiFetch} from "@/utils/bagisto";
 import { CUSTOMER_LOGIN } from "@/graphql/customer/mutations";
 
 export const authOptions: NextAuthOptions = {
@@ -36,6 +36,15 @@ export const authOptions: NextAuthOptions = {
         });
 
         const data = res?.body?.data?.createCustomerLogin?.customerLogin;
+        /* 使用rest api
+        const res = await restApiFetch<any>({
+          api: "/customer/login",
+          variables: { ...input },
+          cache: "no-store",
+        });
+        
+        const data = res?.body;
+        */
 
         if (!data || !data.success || !data.token) {
           throw new Error(data?.message || "Invalid credentials.");

+ 86 - 1
src/utils/bagisto/index.ts

@@ -20,7 +20,7 @@ import {
   FORGET_PASSWORD,
 } from "@/graphql/customer/mutations";
 import { DocumentNode } from "graphql";
-import { GRAPHQL_URL } from "@/utils/constants";
+import { GRAPHQL_URL, REST_API_URL } from "@/utils/constants";
 import {
   GET_FOOTER,
   GET_THEME_CUSTOMIZATION,
@@ -46,6 +46,91 @@ interface PageByUrlKeyResponse {
   pageByUrlKeypages?: PageData[];
 }
 
+// rest api fetch
+export async function restApiFetch<T>({
+  api,
+  cache = "force-cache",
+  headers,
+  tags,
+  variables,
+  isCookies = true,
+  guestToken,
+  revalidate = 60,
+}: {
+  api: string;
+  cache?: RequestCache;
+  headers?: HeadersInit | Record<string, string>;
+  tags?: string[];
+  variables?: ExtractVariables<T>;
+  isCookies?: boolean;
+  guestToken?: string;
+  revalidate?: number;
+}): Promise<{ status: number; body: T } | never> {
+  try {
+    let apiUrl = api.startsWith("http") ? api : `${REST_API_URL}${api}`;
+    let bagistoCartId = "";
+    let accessToken: string | undefined = undefined;
+
+    if (isCookies) {
+      const cookieStore = await cookies();
+      bagistoCartId = cookieStore.get(BAGISTO_SESSION)?.value ?? "";
+      const sessions = (await getServerSession(
+        authOptions,
+      )) as BagistoSession | null;
+      accessToken = sessions?.user?.accessToken;
+    }
+
+    const baseHeaders: Record<string, string> = {
+      "Content-Type": "application/json",
+      "X-STOREFRONT-KEY": STOREFRONT_KEY,
+    };
+
+    if (accessToken) {
+      baseHeaders.Authorization = `Bearer ${accessToken}`;
+    } else if (guestToken) {
+      baseHeaders.Authorization = `Bearer ${guestToken}`;
+    }
+
+    if (bagistoCartId) {
+      baseHeaders.Cookie = `${BAGISTO_SESSION}=${bagistoCartId}`;
+    }
+
+    if (isCookies && headers) {
+      if (headers instanceof Headers) {
+        headers.forEach((value, key) => (baseHeaders[key] = value));
+      } else {
+        Object.assign(baseHeaders, headers);
+      }
+    }
+
+    let param = {};
+    if(variables) {
+      param = {...variables};
+    }
+
+    const result = await fetch(apiUrl, {
+      method: "POST",
+      headers: baseHeaders,
+      body: JSON.stringify(param),
+      cache,
+      next: {
+        revalidate: cache === "no-store" ? 0 : revalidate || 60,
+        ...(tags && { tags }),
+      },
+    });
+
+    const body = await result.json();
+
+    if (body.errors) throw body.errors[0];
+
+    return { status: result.status, body };
+  } catch (e) {
+    throw e;
+  }
+}
+
+
+
 export async function bagistoFetch<T>({
   cache = "force-cache",
   headers,

+ 2 - 0
src/utils/constants.ts

@@ -29,6 +29,7 @@ export const CHECKOUT = {
 export const HIDDEN_PRODUCT_TAG = "nextjs-frontend-hidden";
 export const DEFAULT_OPTION = "Default Title";
 export const BAGISTO_GRAPHQL_API_ENDPOINT = "/api/graphql";
+export const BAGISTO_REST_API_ENDPOINT = "/api/shop";
 
 /**
  * productJsonLd constant
@@ -45,6 +46,7 @@ export const TOKEN = "token";
 export const BASE_URL = process.env.NEXT_PUBLIC_NEXT_AUTH_URL;
 export const baseUrl = process.env.NEXT_PUBLIC_BAGISTO_ENDPOINT;
 export const GRAPHQL_URL = `${(process.env.NEXT_PUBLIC_BAGISTO_ENDPOINT || '').replace(/\/$/, '')}${BAGISTO_GRAPHQL_API_ENDPOINT}`;
+export const REST_API_URL = `${(process.env.NEXT_PUBLIC_BAGISTO_ENDPOINT || '').replace(/\/$/, '')}${BAGISTO_REST_API_ENDPOINT}`;
 export const NEXT_AUTH_SECRET = process.env.NEXT_PUBLIC_NEXT_AUTH_SECRET;
 
 // Server-only: Use non-public env var, fallback to public for backwards compatibility