Skip to content

Instantly share code, notes, and snippets.

@vre2h
Created November 1, 2019 11:46
Show Gist options
  • Save vre2h/32c20e46c62b03a9d8111491b2baa37c to your computer and use it in GitHub Desktop.
Save vre2h/32c20e46c62b03a9d8111491b2baa37c to your computer and use it in GitHub Desktop.
import { ApolloClient } from 'apollo-client';
import { ApolloLink, from } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { setContext } from 'apollo-link-context';
import { RetryLink } from 'apollo-link-retry';
import { loadState } from './localStorage';
export default function generateGraphqlClient({ typeDefs, resolvers }) {
const cache = new InMemoryCache();
const retryLink = new RetryLink({
delay: {
initial: 300,
max: Infinity,
jitter: true,
},
attempts: {
max: 5,
retryIf: error => !!error,
},
});
const authLink = setContext(async (_, { headers }) => {
const token = loadState('token');
// get the authentication token from local storage if it exists
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
Authorization: token,
},
};
});
const errorFormatter = new ApolloLink((operation, forward) =>
forward(operation).map(data => {
if (data && data.errors && data.errors.length > 0) {
throw new Error('GraphQL Operational Error');
}
return data;
})
);
const errorLink = 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}`);
});
const httpLink = new HttpLink({
uri: 'https://mls74aong0.execute-api.us-east-2.amazonaws.com/dev/graphql',
credentials: 'same-origin',
});
const client = new ApolloClient({
cache,
link: from([authLink, errorFormatter, errorLink, retryLink, httpLink]),
resolvers,
typeDefs,
connectToDevTools: true,
queryDeduplication: false,
defaultOptions: {
watchQuery: {
fetchPolicy: 'network-only',
},
},
});
return client;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment