@apollo/client#NormalizedCacheObject TypeScript Examples

The following examples show how to use @apollo/client#NormalizedCacheObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: apollo.ts    From storefront with MIT License 6 votes vote down vote up
export default function createClient({
  initialState = {},
}: { initialState?: NormalizedCacheObject } = {}) {
  if (apolloClient == null) {
    apolloClient = new ApolloClient({
      // eslint-disable-next-line unicorn/prefer-spread
      link: errorLink.concat(
        // eslint-disable-next-line unicorn/prefer-spread
        authLink.concat(
          // eslint-disable-next-line unicorn/prefer-spread
          afterware.concat(
            createHttpLink({
              uri: process.env.GRAPHQL_URL,
              credentials: 'include',
            }),
          ),
        ),
      ),
      cache: new InMemoryCache({ possibleTypes: introspectionResult.possibleTypes }).restore(
        initialState,
      ),
    });
  }
  return apolloClient;
}
Example #2
Source File: [slug].tsx    From storefront with MIT License 6 votes vote down vote up
Page.getInitialProps = async (
  context: NextPageContext & { apolloClient: ApolloClient<NormalizedCacheObject> },
) => {
  const page = await context.apolloClient
    .query<PageQuery, PageQueryVariables>({
      query: PageDocument,
      variables: {
        slug: `${context.query.slug}`,
      },
    })
    .then(({ data }) => {
      if (context.res != null && data?.page == null) {
        context.res.statusCode = 404;
      }
      return data?.page;
    });
  return { page };
};
Example #3
Source File: index.ts    From fullstack-starterkit with MIT License 6 votes vote down vote up
function configureApolloClient(config: Config): ApolloClient<NormalizedCacheObject> {
  const httpLink = new HttpLink({ uri: config.endpoints.https });

  const wsLink = new WebSocketLink({
    uri: config.endpoints.wss,
    options: { reconnect: true }
  });

  const link = split(
    ({ query }) => {
      const definition = getMainDefinition(query);
      return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
    },
    wsLink,
    httpLink
  );

  const client = new ApolloClient({
    link: ApolloLink.from([
      onError(({ graphQLErrors, networkError }) => {
        if (graphQLErrors) {
          graphQLErrors.forEach(({ message, locations, path }) =>
            console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
          );
        }

        if (networkError) {
          console.log(`[Network error]: ${networkError}`);
        }
      }),
      link
    ]),
    cache: new InMemoryCache()
  });

  return client;
}
Example #4
Source File: nextApollo.ts    From liferay-grow with MIT License 6 votes vote down vote up
export function initializeApollo(
  initialState = null,
  createNew = false,
): ApolloClient<NormalizedCacheObject> {
  if (createNew) {
    const client = createApolloClient();

    return client;
  }

  const _apolloClient = createApolloClient();

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // gets hydrated here
  if (initialState) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract();
    // Restore the cache using the data passed from getStaticProps/getServerSideProps
    // combined with the existing cached data
    _apolloClient.cache.restore({ ...existingCache, ...initialState });
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === 'undefined') return _apolloClient;

  return _apolloClient;
}
Example #5
Source File: apolloClient.ts    From next-page-tester with MIT License 6 votes vote down vote up
export function addApolloState<P>(
  client: ApolloClient<NormalizedCacheObject>,
  pageProps: GetStaticPropsResult<P>
) {
  // @ts-expect-error just checking
  if (pageProps.props) {
    // @ts-expect-error injected prop
    pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract();
  }

  return pageProps;
}
Example #6
Source File: index.tsx    From Insomniac-NextJS-boilerplate with MIT License 6 votes vote down vote up
initializeApollo = (
  initialState: NormalizedCacheObject | null = null
): ApolloClient<NormalizedCacheObject> => {
  const _apolloClient = apolloClient ?? createApolloClient();

  // If your page has Next.js data fetching methods that use Apollo Client, the initial state
  // gets hydrated here
  if (initialState && initialState !== null) {
    // Get existing cache, loaded during client side data fetching
    const existingCache = _apolloClient.extract();
    // Restore the cache using the data passed from getStaticProps/getServerSideProps
    // combined with the existing cached data
    _apolloClient.cache.restore({ ...existingCache, ...initialState });
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === 'undefined') return _apolloClient;
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient;

  return _apolloClient;
}
Example #7
Source File: CGraphQLClient.ts    From Cromwell with MIT License 5 votes vote down vote up
/** @internal */
    private apolloClient: ApolloClient<NormalizedCacheObject>;
Example #8
Source File: apollo.ts    From storefront with MIT License 5 votes vote down vote up
apolloClient: ApolloClient<NormalizedCacheObject>
Example #9
Source File: nextApollo.ts    From liferay-grow with MIT License 5 votes vote down vote up
export function useApollo(): ApolloClient<NormalizedCacheObject> {
  const store = initializeApollo();

  return store;
}
Example #10
Source File: ApolloProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 5 votes vote down vote up
dummyClient = new ApolloClient<NormalizedCacheObject>({ cache: new InMemoryCache() })
Example #11
Source File: apolloClient.ts    From next-page-tester with MIT License 5 votes vote down vote up
apolloClient: ApolloClient<NormalizedCacheObject> | undefined = undefined
Example #12
Source File: index.tsx    From Insomniac-NextJS-boilerplate with MIT License 5 votes vote down vote up
apolloClient: ApolloClient<NormalizedCacheObject>
Example #13
Source File: index.tsx    From Insomniac-NextJS-boilerplate with MIT License 5 votes vote down vote up
useApollo = (
  initialState: NormalizedCacheObject
): ApolloClient<NormalizedCacheObject> => {
  const store = useMemo(() => initializeApollo(initialState), [initialState]);
  return store;
}
Example #14
Source File: ApolloExtensionsClient.test.ts    From apollo-cache-policies with Apache License 2.0 4 votes vote down vote up
describe('ApolloExtensionsClient', () => {
  let client: ApolloExtensionsClient<NormalizedCacheObject>;
  let cache: InvalidationPolicyCache;

  beforeEach(() => {
    cache = new InvalidationPolicyCache({
      enableCollections: true,
    });
    client = new ApolloExtensionsClient({
      cache,
      link: ApolloLink.empty(),
    });

    cache.writeQuery({
      query: employeesQuery,
      data: employeesResponse,
    });
  });

  describe('watchFragment', () => {
    describe('with a function subscriber', () => {
      test('should emit the employee object', (done) => {
        const observable = client.watchFragment({
          fragment: gql`
            fragment EmployeeFragment on Employee {
              id
              employee_name
            }
          `,
          id: employee.toRef(),
        });

        const subscription = observable.subscribe((val) => {
          expect(val).toEqual({
            __typename: 'Employee',
            id: employee.id,
            employee_name: employee.employee_name,
          });
          // @ts-ignore Type policies is private
          expect(Object.keys(cache.policies.typePolicies.Query.fields).length).toEqual(1);
          subscription.unsubscribe();
          // @ts-ignore Type policies is private
          expect(Object.keys(cache.policies.typePolicies.Query.fields).length).toEqual(0);
          done();
        });
      });

      test('should emit updates', (done) => {
        const observable = client.watchFragment({
          fragment: gql`
            fragment EmployeeFragment on Employee {
              id
              employee_name
            }
          `,
          id: employee.toRef(),
        });

        const subscription = observable.subscribe((val: any) => {
          if (val.employee_name === 'done') {
            expect(val).toEqual({
              __typename: 'Employee',
              id: employee.id,
              employee_name: 'done',
            });

            subscription.unsubscribe();
            done();
          } else {
            expect(val).toEqual({
              __typename: 'Employee',
              id: employee.id,
              employee_name: employee.employee_name,
            });

            cache.writeFragment({
              fragment: gql`
                fragment UpdateEmployee on Employee {
                  employee_name,
                }
              `,
              id: employee.toRef(),
              data: {
                employee_name: 'done',
              },
            });
          }
        });
      });
    });

    describe('with an object subscriber', () => {
      test('should emit the employee object', (done) => {
        const observable = client.watchFragment({
          fragment: gql`
            fragment EmployeeFragment on Employee {
              id
              employee_name
            }
          `,
          id: employee.toRef(),
        });

        const subscription = observable.subscribe({
          next: (val) => {
            expect(val).toEqual({
              __typename: 'Employee',
              id: employee.id,
              employee_name: employee.employee_name,
            });
            subscription.unsubscribe();
            done();
          },
        });
      });
    });
  });

  describe('watchFragmentWhere', () => {
    describe('with a function subscriber', () => {
      test('should emit the employee object', (done) => {
        const observable = client.watchFragmentWhere<EmployeeType>({
          fragment: gql`
            fragment EmployeeFragment on Employee {
              id
              employee_name
            }
          `,
          filter: {
            employee_name: employee.employee_name,
          },
        });

        const subscription = observable.subscribe((val) => {
          expect(val).toEqual([{
            __typename: 'Employee',
            id: employee.id,
            employee_name: employee.employee_name,
          }]);
          subscription.unsubscribe();
          done();
        });
      });

      test('should emit updates', (done) => {
        const observable = client.watchFragmentWhere<EmployeeType>({
          fragment: gql`
            fragment EmployeeFragment on Employee {
              id
              employee_name
            }
          `,
          filter: {
            employee_name: employee.employee_name,
          },
        });

        const subscription = observable.subscribe((val: any) => {
          if (val.length === 0) {
            subscription.unsubscribe();
            done();
          } else {
            expect(val).toEqual([{
              __typename: 'Employee',
              id: employee.id,
              employee_name: employee.employee_name,
            }]);

            cache.writeFragment({
              fragment: gql`
                fragment UpdateEmployee on Employee {
                  employee_name,
                }
              `,
              id: employee.toRef(),
              data: {
                employee_name: 'done',
              },
            });
          }
        });
      });
    });
  });
});
Example #15
Source File: ApolloProvider.tsx    From mStable-apps with GNU Lesser General Public License v3.0 4 votes vote down vote up
ApolloProvider: FC = ({ children }) => {
  const addErrorNotification = useAddErrorNotification()
  const [persisted, setPersisted] = useState(false)
  const network = useNetwork()
  const previousChainId = usePrevious(network.chainId)
  const networkChanged = previousChainId && network.chainId !== previousChainId

  // Serialized array of failed endpoints to be excluded from the client
  const [failedEndpoints] = useState<string>('')

  const handleError = useCallback(
    (message: string, error?: unknown): void => {
      console.error(message, error)

      // Not significant at the moment; falls back to the hosted service
      if (message.includes('Exhausted list of indexers')) return

      let sanitizedError: string = message
      let body: string | undefined
      if (message.includes('Failed to query subgraph deployment')) {
        sanitizedError = `Subgraph: ${message.split(': ')[1] ?? message}`
      }

      if ((error as { operation?: Operation })?.operation?.operationName) {
        body = `Subgraph: ${(error as { operation: Operation }).operation.operationName}`
      }

      addErrorNotification(sanitizedError, body)
    },
    [addErrorNotification],
  )

  useEffect(() => {
    Promise.all(
      Object.keys(caches).map(clientName =>
        persistCache({
          cache: caches[clientName as keyof ApolloClients] as never,
          storage: window.localStorage as never,
          key: `${network.chainId}-${clientName}`,
        }),
      ),
    )
      .catch(_error => {
        console.warn('Cache persist error', _error)
      })
      .finally(() => {
        setPersisted(true)
      })
  }, [setPersisted, network.chainId])

  const apollo = useMemo<{ ready: true; clients: ApolloClients } | { ready: false }>(() => {
    if (!persisted) return { ready: false }

    // const _failedEndpoints = failedEndpoints.split(',')

    const errorLink = onError(error => {
      const { networkError, graphQLErrors } = error
      if (graphQLErrors) {
        graphQLErrors.forEach(({ message, ..._error }) => {
          // if (_failedEndpoints.includes(ctx.uri)) return

          handleError(message, error)

          // On any GraphQL error, mark the endpoint as failed; this may be
          // excessive, but failed endpoints are merely deprioritised rather than
          // excluded completely.
          // _failedEndpoints.push(ctx.uri)
        })
      }

      if (networkError) {
        handleError(networkError.message, error)
      }
      // setFailedEndpoints(_failedEndpoints.join(','))
    })

    const retryIf = (error: { statusCode: number }) => {
      const doNotRetryCodes = [500, 400]
      return !!error && !doNotRetryCodes.includes(error.statusCode)
    }

    const clients = (Object.keys(caches) as AllGqlEndpoints[])
      .map<[AllGqlEndpoints, ApolloClient<NormalizedCacheObject>]>(name => {
        if (!Object.prototype.hasOwnProperty.call(network.gqlEndpoints, name)) {
          return [name, dummyClient]
        }

        const endpoints = network.gqlEndpoints[name as keyof typeof network['gqlEndpoints']]
        const preferred = endpoints.filter(endpoint => !failedEndpoints.split(',').includes(endpoint))[0]
        const fallback = endpoints[0] // There is always a fallback, even if it failed
        const endpoint = preferred ?? fallback
        const timeoutLink = new ApolloLinkTimeout(30000)

        const endpointNameLink = new ApolloLink((operation, forward) => {
          operation.extensions.endpointName = name
          return forward(operation)
        })
        const httpLink = new HttpLink({ uri: endpoint })
        const retryLink = new RetryLink({ delay: { initial: 1e3, max: 5e3, jitter: true }, attempts: { max: 1, retryIf } })
        const link = ApolloLink.from([endpointNameLink, networkStatusLink, retryLink, timeoutLink, errorLink, httpLink])
        const client = new ApolloClient<NormalizedCacheObject>({
          cache: caches[name],
          link,
          defaultOptions: {
            watchQuery: {
              fetchPolicy: 'cache-and-network',
              errorPolicy: 'all',
            },
            query: {
              fetchPolicy: 'cache-first',
              errorPolicy: 'all',
            },
          },
        })

        return [name, client]
      })
      .reduce<ApolloClients>(
        (prev, [clientName, client]) => ({ ...prev, [clientName as keyof ApolloClients]: client }),
        {} as ApolloClients,
      )

    return { ready: true, clients }
  }, [persisted, failedEndpoints, handleError, network])

  useEffect(() => {
    // Reset caches that can have conflicting keyFields on network change
    // This prevents cached data from a previously selected network being used
    // on a newly-selected network
    if (networkChanged && (apollo as { clients: ApolloClients }).clients) {
      ;(apollo as { clients: ApolloClients }).clients.blocks.resetStore().catch(error => {
        console.error(error)
      })
    }
  }, [apollo, networkChanged])

  return apollo.ready ? <apolloClientsCtx.Provider value={apollo.clients}>{children}</apolloClientsCtx.Provider> : <Skeleton />
}