function createApolloClient()

in app/assets/javascripts/lib/graphql.js [156:316]


function createApolloClient(resolvers = {}, config = {}) {
  const {
    baseUrl,
    cacheConfig = { typePolicies: {}, possibleTypes: {} },
    fetchPolicy = fetchPolicies.CACHE_FIRST,
    typeDefs,
    httpHeaders = {},
    fetchCredentials = 'same-origin',
    path = '/api/graphql',
  } = config;

  let ac = null;
  let uri = `${gon.relative_url_root || ''}${path}`;

  if (baseUrl) {
    // Prepend baseUrl and ensure that `///` are replaced with `/`
    uri = `${baseUrl}${uri}`.replace(/\/{3,}/g, '/');
  }

  if (gon.version) {
    httpHeaders['x-gitlab-version'] = gon.version;
  }

  const httpOptions = {
    uri,
    headers: {
      [csrf.headerKey]: csrf.token,
      ...httpHeaders,
    },
    // fetch won’t send cookies in older browsers, unless you set the credentials init option.
    // We set to `same-origin` which is default value in modern browsers.
    // See https://github.com/whatwg/fetch/pull/585 for more information.
    credentials: fetchCredentials,
  };

  /*
    This custom fetcher intervention is to deal with an issue where we are using GET to access
    eTag polling, but Apollo Client adds excessive whitespace, which causes the
    request to fail on certain self-hosted stacks. When we can move
    to subscriptions entirely or can land an upstream PR, this can be removed.

    Related links
    Bug report: https://gitlab.com/gitlab-org/gitlab/-/issues/329895
    Moving to subscriptions: https://gitlab.com/gitlab-org/gitlab/-/issues/332485
    Apollo Client issue: https://github.com/apollographql/apollo-feature-requests/issues/182
  */

  const fetchIntervention = (url, options) => {
    return fetch(stripWhitespaceFromQuery(url, uri), options);
  };

  const requestLink = ApolloLink.split(
    (operation) => operation.getContext().batchKey,
    new BatchHttpLink({
      ...httpOptions,
      batchKey: (operation) => operation.getContext().batchKey,
      fetch: fetchIntervention,
    }),
    new HttpLink({ ...httpOptions, fetch: fetchIntervention }),
  );

  const uploadsLink = ApolloLink.split(
    (operation) => operation.getContext().hasUpload,
    createUploadLink(httpOptions),
  );

  const performanceBarLink = new ApolloLink((operation, forward) => {
    return forward(operation).map((response) => {
      const httpResponse = operation.getContext().response;

      if (PerformanceBarService.interceptor) {
        PerformanceBarService.interceptor({
          config: {
            url: httpResponse.url,
            operationName: operation.operationName,
            method: operation.getContext()?.fetchOptions?.method || 'POST', // If method is not explicitly set, we default to POST request
          },
          headers: {
            'x-request-id': httpResponse.headers.get('x-request-id'),
            'x-gitlab-from-cache': httpResponse.headers.get('x-gitlab-from-cache'),
          },
        });
      }

      return response;
    });
  });

  const hasSubscriptionOperation = ({ query: { definitions } }) => {
    return definitions.some(
      ({ kind, operation }) => kind === 'OperationDefinition' && operation === 'subscription',
    );
  };

  const hasMutation = (operation) =>
    (operation?.query?.definitions || []).some((x) => x.operation === 'mutation');

  const requestCounterLink = new ApolloLink((operation, forward) => {
    if (hasMutation(operation)) {
      pendingApolloMutations += 1;
    }

    return forward(operation).map((response) => {
      if (hasMutation(operation)) {
        pendingApolloMutations -= 1;
      }
      return response;
    });
  });

  const persistLink = getPersistLink();

  const appLink = ApolloLink.split(
    hasSubscriptionOperation,
    new ActionCableLink(),
    ApolloLink.from(
      [
        getSuppressNetworkErrorsDuringNavigationLink(),
        getInstrumentationLink(),
        sentryBreadcrumbLink,
        correlationIdLink,
        requestCounterLink,
        performanceBarLink,
        new StartupJSLink(),
        apolloCaptchaLink,
        persistLink,
        uploadsLink,
        requestLink,
      ].filter(Boolean),
    ),
  );

  const newCache = new InMemoryCache({
    ...cacheConfig,
    typePolicies: {
      ...typePolicies,
      ...cacheConfig.typePolicies,
    },
    possibleTypes: {
      ...possibleTypes,
      ...cacheConfig.possibleTypes,
    },
  });

  ac = new ApolloClient({
    typeDefs,
    link: appLink,
    connectToDevTools: process.env.NODE_ENV !== 'production',
    cache: newCache,
    resolvers,
    defaultOptions: {
      query: {
        fetchPolicy,
      },
    },
  });

  acs.push(ac);

  return { client: ac, cache: newCache };
}