41 lines
1.2 KiB
JavaScript
41 lines
1.2 KiB
JavaScript
|
import { ApolloClient } from 'apollo-client'
|
||
|
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 { ApolloLink } from 'apollo-link'
|
||
|
|
||
|
const httpLink = new HttpLink({
|
||
|
uri: process.env.REACT_APP_GRAPHQL_URI,
|
||
|
credentials: 'same-origin',
|
||
|
})
|
||
|
|
||
|
const linkError = onError(({ graphQLErrors, networkError }) => {
|
||
|
if (graphQLErrors)
|
||
|
graphQLErrors.map(({ message, locations, path }) =>
|
||
|
console.log(
|
||
|
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
|
||
|
)
|
||
|
)
|
||
|
if (networkError) console.log(`[Network error]: ${networkError}`)
|
||
|
})
|
||
|
|
||
|
const authLink = setContext((_, { headers }) => {
|
||
|
// get the authentication token from local storage if it exists
|
||
|
const token = localStorage.getItem('token')
|
||
|
// return the headers to the context so httpLink can read them
|
||
|
return {
|
||
|
headers: {
|
||
|
...headers,
|
||
|
authorization: token ? `Bearer ${token}` : '',
|
||
|
},
|
||
|
}
|
||
|
})
|
||
|
|
||
|
const client = new ApolloClient({
|
||
|
link: ApolloLink.from([linkError, authLink.concat(httpLink)]),
|
||
|
cache: new InMemoryCache(),
|
||
|
})
|
||
|
|
||
|
export default client
|