1
Fork 0
photoview/ui/src/apolloClient.js

79 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-07-07 15:54:39 +02:00
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
2019-07-20 18:25:15 +02:00
import { WebSocketLink } from 'apollo-link-ws'
2019-07-07 15:54:39 +02:00
import { onError } from 'apollo-link-error'
import { setContext } from 'apollo-link-context'
2019-07-20 18:25:15 +02:00
import { ApolloLink, split } from 'apollo-link'
import { getMainDefinition } from 'apollo-utilities'
2019-07-07 15:54:39 +02:00
const httpLink = new HttpLink({
2019-08-09 18:07:14 +02:00
uri: process.env.GRAPHQL_ENDPOINT,
2019-07-07 15:54:39 +02:00
credentials: 'same-origin',
})
2019-08-09 18:07:14 +02:00
console.log('GRAPHQL ENDPOINT', process.env.GRAPHQL_ENDPOINT)
2020-01-19 22:58:31 +01:00
const apiProtocol = new URL(process.env.GRAPHQL_ENDPOINT).protocol
2019-08-09 18:07:14 +02:00
let websocketUri = new URL(process.env.GRAPHQL_ENDPOINT)
2020-01-19 22:58:31 +01:00
websocketUri.protocol = apiProtocol === 'https:' ? 'wss:' : 'ws:'
2019-08-09 18:07:14 +02:00
2019-07-20 18:25:15 +02:00
const wsLink = new WebSocketLink({
2019-08-09 18:07:14 +02:00
uri: websocketUri,
2019-07-20 18:25:15 +02:00
credentials: 'same-origin',
options: {
reconnect: true,
connectionParams: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
},
})
const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
wsLink,
httpLink
)
2019-07-07 15:54:39 +02:00
const linkError = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${JSON.stringify(
locations
)} Path: ${path}`
2019-07-07 15:54:39 +02:00
)
)
2019-07-31 00:55:48 +02:00
if (networkError) {
2019-07-20 18:25:15 +02:00
console.log(`[Network error]: ${JSON.stringify(networkError)}`)
2019-07-31 00:55:48 +02:00
localStorage.removeItem('token')
}
2019-07-07 15:54:39 +02:00
})
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({
2019-07-20 18:25:15 +02:00
link: ApolloLink.from([linkError, authLink.concat(link)]),
2019-07-07 15:54:39 +02:00
cache: new InMemoryCache(),
})
export default client