ApolloClientServer.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { GRAPHQL_URL } from "@/utils/constants";
  2. import { HttpLink,ApolloLink } from "@apollo/client";
  3. import { SetContextLink } from "@apollo/client/link/context";
  4. import {
  5. registerApolloClient,
  6. ApolloClient,
  7. InMemoryCache,
  8. } from "@apollo/client-integration-nextjs";
  9. // apollo client 底层还是调的nextjs的fetch函数。
  10. // apollo client 的缓存策略是建立在nextjs缓存策略之上的,相当于两个沙盒
  11. // 这里注册的是服务端的apollo client。项目中服务端使用的apollo client只是用于query 查询,而且不需要Authorization
  12. export const { getClient, query, PreloadQuery } = registerApolloClient(() => {
  13. const httpLink = new HttpLink({
  14. uri: GRAPHQL_URL,
  15. credentials: "include",
  16. /*
  17. fetchOptions: {
  18. // Optional: Next.js-specific fetch options for caching and revalidation
  19. // See: https://nextjs.org/docs/app/api-reference/functions/fetch
  20. },
  21. */
  22. });
  23. const authLink = new SetContextLink((prevContext, operation) => {
  24. const storefrontKey =
  25. process.env.BAGISTO_STOREFRONT_KEY ||
  26. process.env.NEXT_PUBLIC_BAGISTO_STOREFRONT_KEY ||
  27. "";
  28. return {
  29. headers: {
  30. ...prevContext.headers,
  31. "X-STOREFRONT-KEY": storefrontKey,
  32. },
  33. };
  34. });
  35. const link = ApolloLink.from([authLink, httpLink]);
  36. return new ApolloClient({
  37. cache: new InMemoryCache(),
  38. link: link
  39. });
  40. });