import { GRAPHQL_URL } from "@/utils/constants"; import { HttpLink,ApolloLink } from "@apollo/client"; import { SetContextLink } from "@apollo/client/link/context"; import { registerApolloClient, ApolloClient, InMemoryCache, } from "@apollo/client-integration-nextjs"; // apollo client 底层还是调的nextjs的fetch函数。 // apollo client 的缓存策略是建立在nextjs缓存策略之上的,相当于两个沙盒 // 这里注册的是服务端的apollo client。项目中服务端使用的apollo client只是用于query 查询,而且不需要Authorization export const { getClient, query, PreloadQuery } = registerApolloClient(() => { const httpLink = new HttpLink({ uri: GRAPHQL_URL, credentials: "include", /* fetchOptions: { // Optional: Next.js-specific fetch options for caching and revalidation // See: https://nextjs.org/docs/app/api-reference/functions/fetch }, */ }); const authLink = new SetContextLink((prevContext, operation) => { const storefrontKey = process.env.BAGISTO_STOREFRONT_KEY || process.env.NEXT_PUBLIC_BAGISTO_STOREFRONT_KEY || ""; return { headers: { ...prevContext.headers, "X-STOREFRONT-KEY": storefrontKey, }, }; }); const link = ApolloLink.from([authLink, httpLink]); return new ApolloClient({ cache: new InMemoryCache(), link: link }); });