浏览代码

底部footer数据请求方法修改;删除无用代码

fogwind 1 周之前
父节点
当前提交
45955f5a8f

+ 0 - 5
src/app/(public)/category/[slug]/[id]/page.tsx

@@ -17,11 +17,6 @@ import {
   GET_CATEGORY_ATTR_FILTERS,
   CATEGORY_PRODUCTS,
 } from "@/graphql";
-import {
-  // cachedGraphQLRequest,
-  // cachedCategoryRequest,
-  // getFilterAttributes,
-} from "@/utils/hooks/useCache";
 import { newSortByFields } from "@utils/constants";
 // import { CategoryDetail } from "@components/theme/search/CategoryDetail";
 import CategoryDesc from "./_components/CategoryDesc";

+ 32 - 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 { env } from "@/env";
 import LogoIcon from "@components/common/icons/LogoIcon";
 import FaceBookIcon from "@components/common/icons/social-icon/FaceBookIcon";
@@ -9,13 +16,36 @@ import TwitterIcon from "@components/common/icons/social-icon/TwitterIcon";
 import Subscribe from "./Subscribe";
 import FooterMenu from "./FooterMenu";
 
+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 = env.STORE_NAME;
 
 

+ 0 - 130
src/lib/graphql-fetch.ts

@@ -1,130 +0,0 @@
-
-import { type DocumentNode } from "graphql";
-import {
-  type OperationVariables,
-  ApolloClient
-} from "@apollo/client";
-import type {GraphqlRequestResult} from "@/types/graphqlFetch/type";
-import {getClient} from "@/lib/ApolloClientServer";
-
-
-
-/* 定义自己的context类型
-import "@apollo/client";
-import { HttpLink } from "@apollo/client";
-declare module "@apollo/client" {
-  interface DefaultContext extends HttpLink.ContextOptions {}
-}
-*/
-// Comprehensive error handling example. https://www.apollographql.com/docs/react/data/error-handling
-
-export type CacheLifePreset =
-  | "seconds"
-  | "minutes"
-  | "hours"
-  | "days"
-  | "weeks"
-  | "max";
-
-export type CacheLifeOption = number | CacheLifePreset;
-
-export function getRevalidateTime(
-  life?: CacheLifeOption
-): number | false {
-  if (!life) return false;
-  if (typeof life === "number") return life;
-
-  switch (life) {
-    case "seconds":
-      return 10;
-    case "minutes":
-      return 60;
-    case "hours":
-      return 3600;
-    case "days":
-      return 86400;
-    case "weeks":
-      return 604800;
-    case "max":
-      return false;
-    default:
-      return false;
-  }
-}
-
-export interface GraphQLRequestOptions {
-  tags?: string[];
-  life?: CacheLifeOption;
-  noCache?: boolean;
-  context?: Record<string, unknown>;
-  fetchPolicy?:
-  | "cache-first"
-  | "network-only"
-  | "no-cache"
-  | "cache-only";
-}
-
-export async function graphqlRequest<
-  TData = unknown,
-  TVariables extends OperationVariables = OperationVariables
->(
-  query: DocumentNode,
-  variables?: TVariables,
-  options?: GraphQLRequestOptions
-): Promise<GraphqlRequestResult<TData>> {
-  const client = getClient();
-  let resData;
-  const revalidate = getRevalidateTime(options?.life);
-  let queryOption: ApolloClient.QueryOptions<TData> = {
-    query,
-    variables,
-    fetchPolicy: "network-only",
-    context: {
-      fetchOptions: {
-        next: {
-          revalidate,
-          tags: options?.tags,
-        },
-      },
-    }
-  };
-
-  if (options?.noCache) {
-    /***
-     * client.query的参数是一个对象:
-     * {query, variables, context, fetchPolicy, errorPolicy}
-     * context.fetchOptions 可以设置nextjs fetch的缓存策略 https://www.apollographql.com/docs/react/integrations/nextjs
-     * context: {
-        fetchOptions: {
-          next: {
-            revalidate: 60,      // 对应 life: 'minutes'
-            tags: ['posts'],     // 对应 tags 选项
-          },
-        },
-      },
-     */
-    queryOption = {
-      query,
-      variables,
-      context: options?.context,
-      fetchPolicy: "no-cache", // 跳过 apollo client 的缓存,直接调fetch
-    };
-  }
-
-  if (options?.context) {
-    throw new Error(
-      "graphqlRequest: Caching with `context` is unsafe. Use noCache instead."
-    );
-  }
-  try {
-      // Promise-based APIs (e.g. client.query, client.mutate) - Errors either reject the promise or are returned in the result as the error field.
-      // 如果错误被reject 则会进入catch
-      const result: ApolloClient.QueryResult<TData> = await client.query(queryOption);
-
-      resData = result.data || null;
-      return {data: resData, error: result.error? result.error.message : '' };
-  } catch (error) {
-    throw error;
-  }
-}
-

+ 0 - 4
src/types/graphqlFetch/type.ts

@@ -1,7 +1,3 @@
-export interface GraphqlRequestResult<TData = unknown> {
-  data: TData | null;
-  error: string | undefined;
-}
 
 export interface FetchGraphqlError {
     message: string;

+ 8 - 46
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";
@@ -113,12 +109,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};
 
@@ -128,7 +118,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) {
@@ -198,10 +190,6 @@ 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};
     
@@ -211,6 +199,8 @@ export async function serverGraphqlFetch<
         baseHeaders['Authorization'] = `Bearer ${tokenRes.token}`;
       }
     }
+  try {
+    const queryString = typeof query === "string" ? query : print(query);
 
     if (headers) {
       if (headers instanceof Headers) {
@@ -276,11 +266,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};
 
@@ -291,10 +276,10 @@ export async function bagistoFetch<T>({
       }
 
     }
+  try {
+    const queryString =
+      typeof query === "string" ? query : print(query);
     
-
-    
-
     if (headers) {
       if (headers instanceof Headers) {
         headers.forEach((value, key) => (baseHeaders[key] = value));
@@ -351,30 +336,7 @@ 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[]> {

+ 0 - 134
src/utils/hooks/useCache.ts

@@ -1,134 +0,0 @@
-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[];
-  life: CacheLifeOption;
-}
-
-/**
- * Cache configuration for different pages and queries
- * Centralized management of cache tags and revalidation times
- */
-export const PAGE_CACHE_CONFIG: Record<string, PageCacheConfig> = {
-  // Home page
-  home: {
-    tags: ["home-page"],
-    life: "hours",
-  },
-
-  // Product pages
-  product: {
-    tags: ["all-products"],
-    life: "hours",
-  },
-
-  // Category/Collection pages
-  category: {
-    tags: ["categories"],
-    life: "hours",
-  },
-
-  // Static content
-  static: {
-    tags: ["static-content"],
-    life: "days",
-  },
-
-  // Search results
-  search: {
-    tags: ["search-results"],
-    life: "hours",
-  },
-};
-
-/**
- * Helper to get cache config for a specific page
- */
-export function getPageCacheConfig(
-  page: keyof typeof PAGE_CACHE_CONFIG,
-): PageCacheConfig {
-  return PAGE_CACHE_CONFIG[page];
-}
-
-/**
- * Helper to create dynamic product cache config with specific product identifier
- */
-// export function getProductCacheConfig(productId: string): PageCacheConfig {
-//   return {
-//     tags: ["products", `product-${productId}`],
-//     life: "hours",
-//   };
-// }
-export function getProductCacheConfig(): {noCache: boolean} {
-  return {noCache: true};
-}
-/**
- * Helper to create dynamic category cache config with specific category identifier
- */
-export function getCategoryCacheConfig(categoryId: string): PageCacheConfig {
-  return {
-    tags: ["categories", `category-${categoryId}`],
-    life: "hours",
-  };
-}
-
-/**
- * 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);
-}
-
-
-
-/**
- * Wrapper for category-specific queries with dynamic cache tags
- */
-export async function cachedCategoryRequest<
-  TData = unknown,
-  TVariables extends OperationVariables = OperationVariables,
->(
-  categoryId: string,
-  query: DocumentNode,
-  variables?: TVariables,
-): Promise<GraphqlRequestResult<TData>> {
-  const config = getCategoryCacheConfig(categoryId);
-  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,
-    })),
-  }));
-}