@apollo/client#ApolloLink JavaScript Examples

The following examples show how to use @apollo/client#ApolloLink. 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: client.js    From nextjs-boilerplate with MIT License 7 votes vote down vote up
client = () =>
  new ApolloClient({
    credentials: "include",
    link: ApolloLink.from([
      new HttpLink({
        uri: settings.graphql.uri,
        credentials: "include",
      }),
    ]),
    cache: new InMemoryCache(),
    defaultOptions: {
      watchQuery: {
        errorPolicy: "all",
        fetchPolicy: "network-only",
      },
      query: {
        errorPolicy: "all",
        fetchPolicy: "network-only",
      },
      mutate: {
        errorPolicy: "all",
      },
    },
  })
Example #2
Source File: client.js    From gatsby-apollo-wpgraphql-jwt-starter with MIT License 6 votes vote down vote up
authMiddleware = new ApolloLink((operation, forward) => {
  // get the authentication token from local storage if it exists
  const token = getInMemoryAuthToken()

  operation.setContext({
    headers: {
      Authorization: token ? `Bearer ${token}` : '',
    },
  })

  return forward(operation)
})
Example #3
Source File: ApolloClient.js    From nextjs-woocommerce with GNU General Public License v3.0 6 votes vote down vote up
middleware = new ApolloLink((operation, forward) => {
  /**
   * If session data exist in local storage, set value as session header.
   * Here we also delete the session if it is older than 24 hours
   */
  const session = process.browser ? localStorage.getItem('woo-session') : null;
  const sessionAge = process.browser
    ? localStorage.getItem('woo-session-expiry')
    : null;
  const todaysDate = new Date();
  const oneDay = 60 * 60 * 24 * 1000;
  const olderThan24h = new Date(todaysDate) - new Date(sessionAge) > oneDay;

  if (olderThan24h && process.browser) {
    localStorage.removeItem('woo-session');
    localStorage.removeItem('woo-session-expiry');
  }
  if (session) {
    operation.setContext(() => ({
      headers: {
        'woocommerce-session': `Session ${session}`,
      },
    }));
  }
  return forward(operation);
})
Example #4
Source File: ApolloClient.js    From nextjs-woocommerce with GNU General Public License v3.0 6 votes vote down vote up
afterware = new ApolloLink((operation, forward) =>
  forward(operation).map((response) => {
    /**
     * Check for session header and update session in local storage accordingly.
     */
    const context = operation.getContext();
    const {
      response: { headers },
    } = context;

    const session = headers.get('woocommerce-session');

    if (session && process.browser) {
      // Remove session data if session destroyed.
      if ('false' === session) {
        localStorage.removeItem('woo-session');
        // Update session new data if changed.
      } else if (localStorage.getItem('woo-session') !== session) {
        localStorage.setItem('woo-session', headers.get('woocommerce-session'));
        localStorage.setItem('woo-session-expiry', new Date());
      }
    }
    return response;
  })
)
Example #5
Source File: link.js    From ReactNativeApolloOnlineStore with MIT License 5 votes vote down vote up
authLink = new ApolloLink((operation, forward) => {
  operation.setContext({
    headers: {
      authorization: 'bearer xxxx',
    },
  });
  return forward(operation);
})
Example #6
Source File: ApolloProvider.js    From climatescape.org with MIT License 5 votes vote down vote up
ApolloProvider = ({ children }) => {
  const { getTokenSilently, isAuthenticated } = useAuth0()
  const {
    site: { siteMetadata },
  } = useStaticQuery(graphql`
    query ApolloProviderQuery {
      site {
        siteMetadata {
          graphqlUri
        }
      }
    }
  `)

  const tokenLink = setContext(async () => {
    if (!isAuthenticated) return {}

    const token = await getTokenSilently()

    if (!token) return {}

    return {
      headers: { Authorization: `Bearer ${token}` },
    }
  })

  const errorLink = onError(error => {
    console.error("Apollo error", error) // eslint-disable-line no-console
  })

  // TODO: This total hack can be removed once we fix site builds with https
  // for now, the ENV var is insecure by default but we need to secure it
  // for the client in order to prevent "mixed content" errors
  const uri = siteMetadata.graphqlUri.replace("http://", "https://")
  const httpLink = new HttpLink({
    uri,
    fetch,
  })

  const apolloClient = new ApolloClient({
    link: ApolloLink.from([tokenLink, errorLink, httpLink]),
    cache: new InMemoryCache(),
  })

  return (
    <VanillaApolloProvider client={apolloClient}>
      {children}
    </VanillaApolloProvider>
  )
}
Example #7
Source File: client.js    From horondi_client_fe with MIT License 5 votes vote down vote up
client = new ApolloClient({
  fetch,
  link: ApolloLink.from([terminatingLink]),
  cache: new InMemoryCache({
    addTypename: false,
    fragmentMatcher
  })
})
Example #8
Source File: apolloClient.js    From realworld with MIT License 5 votes vote down vote up
function createApolloClient(ctx) {
  const ssrMode = typeof window === 'undefined';

  return new ApolloClient({
    assumeImmutableResults: true,
    connectToDevTools: !ssrMode && process.env.NODE_ENV !== 'production',
    ssrMode,
    name: 'Condit',
    version: '1.0.0',
    link: ApolloLink.from([
      setContext(() => {
        const { authorization } = ssrMode
          ? cookie.parse(ctx?.req?.headers?.cookie ?? '')
          : cookie.parse(document.cookie);
        return {
          headers: { authorization },
        };
      }),
      new HttpLink({
        uri: process.env.NEXT_PUBLIC_GRAPHQL_URL, // Server URL (must be absolute)
        credentials: 'omit', // Additional fetch() options like `credentials` or `headers`
      }),
    ]),
    cache: new InMemoryCache({
      resultCaching: true,
      dataIdFromObject(object) {
        switch (object.__typename) {
          case 'Article':
            return `${object.__typename}:${object.slug}`;
          case 'User':
            return `${object.__typename}:${object.username}`;
          default:
            return defaultDataIdFromObject(object);
        }
      },
      typePolicies: {
        Article: {
          keyFields: ['slug'],
        },
        User: {
          keyFields: ['username'],
        },
        Query: {
          fields: {
            articlesConnection: relayStylePagination(),
            articleBySlug(_, { args, toReference }) {
              return toReference({ __typename: 'Article', slug: args.slug });
            },
            comment(_, { args, toReference }) {
              return toReference({ __typename: 'Comment', id: args.id });
            },
            feedConnection: relayStylePagination(),
            userByUsername(_, { args, toReference }) {
              return toReference({
                __typename: 'User',
                username: args.username,
              });
            },
            tag(_, { args, toReference }) {
              return toReference({ __typename: 'Tag', id: args.id });
            },
          },
        },
      },
    }),
  });
}