client.js 826 B

12345678910111213141516171819202122232425262728293031
  1. import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
  2. import { setContext } from '@apollo/client/link/context';
  3. import { onError } from '@apollo/client/link/error';
  4. import {GRAPHQL_URL} from '../config';
  5. const httpLink = new HttpLink({ uri: GRAPHQL_URL });
  6. const authLink = setContext(async (_, { headers }) => {
  7. const token = localStorage.authToken;
  8. return {
  9. headers: {
  10. ...headers,
  11. authorization: token ? `Bearer ${token}` : '',
  12. },
  13. };
  14. });
  15. const errorLink = onError(({ operation, graphQLErrors }) => {
  16. console.warn(
  17. `Query: ${operation.operationName}, graphQLErrors: "${JSON.stringify(
  18. graphQLErrors,
  19. )}".`,
  20. );
  21. });
  22. const client = new ApolloClient({
  23. link: errorLink.concat(authLink).concat(httpLink),
  24. cache: new InMemoryCache(),
  25. });
  26. export default client;