Browse Source

footer 数据获取调用的方法修改

zgl 15 hours ago
parent
commit
bdc0d1cb50
4 changed files with 49 additions and 96 deletions
  1. 3 1
      README.md
  2. 33 2
      src/components/layout/footer/index.tsx
  3. 12 53
      src/utils/bagisto/index.ts
  4. 1 40
      src/utils/hooks/useCache.ts

+ 3 - 1
README.md

@@ -357,7 +357,9 @@ useEffect 只会在客户端执行,具体是在浏览器绘制后执行,服
     ---- 47 条 请求方法已经扩展是否携带token的参数,但是不再添加对于token的有效性校验,以后端接口返回的错误为依据判断有效性
 48. 游客token的创建优化(想在服务端创建写入token)--- 已完成
 49. 结账页地址模块未登录用户输入邮箱后判断是否注册过,如果注册过让用户登录;--- 已完成
-50. 注册接口,提交的phone是 +1 345345345 格式,但是保存到数据库后成了+1345345345
+50. 注册接口,提交的phone是 +1 345345345 格式,但是保存到数据库后成了+1345345345  -- 后端已处理
+51. serverGraphqlFetch 方法中关于token和x-currency, x-channel, x-local 是从cookie中获取的,但是next.js build时检测到调用cookie,会将页面强制转换成动态渲染。
+    也就是说没有缓存了。这个问题需要验证和研究,暂时先不管。
 
 
 > 39,40 参考 https://chatgpt.com/share/6a4f0637-ad28-83ea-ad44-423740795054

+ 33 - 2
src/components/layout/footer/index.tsx

@@ -1,6 +1,13 @@
 import Link from "next/link";
 import { Suspense } from "react";
-import { getThemeCustomization } from "@/utils/bagisto";
+import { serverGraphqlFetch } from "@/utils/bagisto";
+import type {
+  GetFooterResponse,
+  ThemeCustomizationResult
+} from "@/types/theme/theme-customization";
+import {
+  GET_FOOTER
+} from "@/graphql";
 import LogoIcon from "@components/common/icons/LogoIcon";
 import FaceBookIcon from "@components/common/icons/social-icon/FaceBookIcon";
 import InstaGramIcon from "@components/common/icons/social-icon/InstaGramIcon";
@@ -9,12 +16,36 @@ import Subscribe from "./Subscribe";
 import FooterMenu from "./FooterMenu";
 const { COMPANY_NAME, SITE_NAME } = process.env;
 
+async function getFooterData(): Promise<ThemeCustomizationResult> {
+ 
+    const [{data: footerRes}, {data:servicesRes}] = await Promise.all([
+      serverGraphqlFetch<GetFooterResponse,{type: string;}>({
+        query: GET_FOOTER,
+        variables:{
+          type: "footer_links",
+        },
+        takeAuthorization: false
+      }),
+      serverGraphqlFetch<GetFooterResponse,{type: string;}>({
+        query: GET_FOOTER,
+        variables:{
+          type: "services_content",
+        },
+        takeAuthorization: false
+      }),
+    ]);
+    return {
+      footer_links: footerRes,
+      services_content: servicesRes,
+    };
+}
+
 export default async function Footer() {
   const currentYear = new Date().getFullYear();
   const copyrightDate = 2010 + (currentYear > 2010 ? `-${currentYear}` : "");
   const skeleton =
     "w-full h-6 animate-pulse rounded bg-neutral-200 dark:bg-neutral-700";
-  const menu = await getThemeCustomization();
+  const menu = await getFooterData();
   const copyrightName = COMPANY_NAME || SITE_NAME || "";
 
 

+ 12 - 53
src/utils/bagisto/index.ts

@@ -12,14 +12,10 @@ import {
   CURRENT_CHANNEL,
 } from "@/utils/constants";
 import {
-  GET_FOOTER,
   PAGE_BY_URL_KEY,
 } from "@/graphql";
 import { SUBSCRIBE_TO_NEWSLETTER } from "@/graphql/theme/mutations";
-import { cachedGraphQLRequest } from "@/utils/hooks/useCache";
 import type {
-  GetFooterResponse,
-  ThemeCustomizationResult,
   PageData,
 } from "@/types/theme/theme-customization";
 import type {FetchGraphqlResult} from "@/types/graphqlFetch/type";
@@ -128,12 +124,6 @@ export async function restApiFetch<T>({
   revalidate?: number;
   takeAuthorization?: boolean;
 }): Promise<{ status: number; body: ExtractRestFulData<T> } | never> {
-  try {
-    const apiUrl = api.startsWith("http") ? api : `${REST_API_URL}${api}`;
-    const url = new URL(apiUrl);
-
-    
-
     const headerRes = await getBaseHeader();
     const baseHeaders: Record<string, string> = {...headerRes};
 
@@ -143,7 +133,9 @@ export async function restApiFetch<T>({
         baseHeaders.Authorization = `Bearer ${tokenRes.token}`;
       }
     }
-
+  try {
+    const apiUrl = api.startsWith("http") ? api : `${REST_API_URL}${api}`;
+    const url = new URL(apiUrl);
 
     if (headers) {
       if (headers instanceof Headers) {
@@ -213,19 +205,16 @@ export async function serverGraphqlFetch<
   revalidate?: number;
   takeAuthorization?: boolean;
 }): Promise<FetchGraphqlResult<TData>> {
-  try {
-    const queryString = typeof query === "string" ? query : print(query);
-
-    
-    const headerRes = await getBaseHeader();
-    const baseHeaders: Record<string, string> = {...headerRes};
-    
-    if(takeAuthorization) {
+  const headerRes = await getBaseHeader();
+  const baseHeaders: Record<string, string> = {...headerRes};
+  if(takeAuthorization) {
       const tokenRes = await getAuthorizationToken();
       if (tokenRes.token) {
         baseHeaders['Authorization'] = `Bearer ${tokenRes.token}`;
       }
-    }
+  }
+  try {
+    const queryString = typeof query === "string" ? query : print(query);
 
     if (headers) {
       if (headers instanceof Headers) {
@@ -291,11 +280,6 @@ export async function bagistoFetch<T>({
   takeAuthorization?: boolean;
   revalidate?: number;
 }): Promise<{ status: number; body: ExtractGraphqlData<T> } | never> {
-  try {
-    const queryString =
-      typeof query === "string" ? query : print(query);
-
-    
     const headerRes = await getBaseHeader();
     const baseHeaders: Record<string, string> = {...headerRes};
 
@@ -306,9 +290,9 @@ export async function bagistoFetch<T>({
       }
 
     }
-    
-
-    
+  try {
+    const queryString =
+      typeof query === "string" ? query : print(query);
 
     if (headers) {
       if (headers instanceof Headers) {
@@ -366,31 +350,6 @@ export async function subscribeUser(
   }
 }
 
-export async function getThemeCustomization(): Promise<ThemeCustomizationResult> {
-  try {
-    const [{data: footerRes}, {data:servicesRes}] = await Promise.all([
-      cachedGraphQLRequest<GetFooterResponse>("static", GET_FOOTER, {
-        type: "footer_links",
-      }),
-      cachedGraphQLRequest<GetFooterResponse>("static", GET_FOOTER, {
-        type: "services_content",
-      }),
-    ]);
-
-    return {
-      footer_links: footerRes,
-      services_content: servicesRes,
-    };
-  } catch (err) {
-    console.error("ThemeCustomization Error:", err);
-  }
-
-  return {
-    footer_links: null,
-    services_content: null,
-  };
-}
-
 
 export async function getPage(input: { urlKey: string }): Promise<PageData[]> {
   const res = await bagistoFetch<{

+ 1 - 40
src/utils/hooks/useCache.ts

@@ -1,7 +1,7 @@
 import { type DocumentNode, type OperationVariables } from "@apollo/client";
 import { graphqlRequest, type CacheLifeOption } from "@/lib/graphql-fetch";
 import type {GraphqlRequestResult} from "@/types/graphqlFetch/type";
-import { GET_FILTER_ATTRIBUTES } from "@/graphql";
+
 
 export interface PageCacheConfig {
   tags: string[];
@@ -75,21 +75,6 @@ export function getCategoryCacheConfig(categoryId: string): PageCacheConfig {
   };
 }
 
-/**
- * Wrapper hook for graphqlRequest with automatic cache management
- * Usage: const data = await cachedGraphQLRequest('home', query, variables);
- */
-export async function cachedGraphQLRequest<
-  TData = unknown,
-  TVariables extends OperationVariables = OperationVariables,
->(
-  page: keyof typeof PAGE_CACHE_CONFIG,
-  query: DocumentNode,
-  variables?: TVariables,
-): Promise<GraphqlRequestResult<TData>> {
-  const config = getPageCacheConfig(page);
-  return graphqlRequest<TData, TVariables>(query, variables, config);
-}
 
 
 
@@ -108,27 +93,3 @@ export async function cachedCategoryRequest<
   return graphqlRequest<TData, TVariables>(query, variables, config);
 }
 
-/**
- * Fetches filter attributes (color, size, brand) for product filtering
- *
- * @returns Promise with formatted filter attributes
- */
-export async function getFilterAttributes() {
-  const {data: filterData } = await cachedGraphQLRequest<{
-    color: any;
-    size: any;
-    brand: any;
-  }>("static", GET_FILTER_ATTRIBUTES, { locale: "en" });
-
-  const attributes = [filterData?.color, filterData?.size, filterData?.brand];
-
-  return attributes.filter(Boolean).map((attr) => ({
-    id: attr.id,
-    code: attr.code,
-    adminName: attr.code.toUpperCase(),
-    options: attr.options.edges.map((o: any) => ({
-      id: o.node.id,
-      adminName: o.node.adminName,
-    })),
-  }));
-}