client.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { ApolloClient } from '@apollo/client/core'
  3. import type { CacheInitializerModules } from '#shared/types/server/apollo/client.ts'
  4. import createCache from './cache.ts'
  5. import link from './link.ts'
  6. import type { NormalizedCacheObject } from '@apollo/client/core'
  7. let apolloClient: ApolloClient<NormalizedCacheObject>
  8. export const createApolloClient = (
  9. cacheInitializerModules: CacheInitializerModules = {},
  10. ) => {
  11. const cache = createCache(cacheInitializerModules)
  12. apolloClient = new ApolloClient({
  13. connectToDevTools: process.env.NODE_ENV !== 'production',
  14. link,
  15. cache,
  16. queryDeduplication: true,
  17. defaultOptions: {
  18. // always refresh query results from the server
  19. // https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy
  20. watchQuery: {
  21. fetchPolicy: 'cache-and-network',
  22. nextFetchPolicy(currentFetchPolicy, { initialFetchPolicy, reason }) {
  23. // If the initial fetch policy is cache-first, switch to cache-only to not trigger unwanted network requests.
  24. if (
  25. initialFetchPolicy === 'cache-first' &&
  26. reason !== 'variables-changed'
  27. ) {
  28. return 'cache-only'
  29. }
  30. // Leave all other fetch policies unchanged.
  31. return currentFetchPolicy
  32. },
  33. },
  34. },
  35. })
  36. return apolloClient
  37. }
  38. export const getApolloClient = () => {
  39. return apolloClient
  40. }
  41. export const clearApolloClientStore = async () => {
  42. await apolloClient.clearStore()
  43. }