Skip to content

Instantly share code, notes, and snippets.

@lovegrovegeorge
Created May 22, 2018 10:21
Show Gist options
  • Save lovegrovegeorge/9be7efb6d8b5cfb7e499f23e1dd80cfe to your computer and use it in GitHub Desktop.
Save lovegrovegeorge/9be7efb6d8b5cfb7e499f23e1dd80cfe to your computer and use it in GitHub Desktop.
React Native Apollo client setup
import { createHttpLink } from 'apollo-link-http'
import { ApolloLink, split, concat } from 'apollo-link'
import { ApolloClient } from 'apollo-client'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { onError } from 'apollo-link-error'
import { withClientState } from 'apollo-link-state'
import env from '../env.json'
import { defaults, resolvers } from './local-state'
function hasSubscriptionOperation({ query }) {
const { kind, operation } = getMainDefinition(query)
return kind === 'OperationDefinition' && operation === 'subscription'
}
export function createClient(token) {
const httpLink = createHttpLink({ uri: env.API_ENDPOINT })
const wsLink = new WebSocketLink({
uri: env.API_SUBSCRIPTION_ENDPOINT,
options: {
reconnect: true,
connectionParams: {
authorization: token ? `Bearer ${token}` : ''
}
}
})
const link = split(
hasSubscriptionOperation,
wsLink,
httpLink
)
const stateLink = withClientState({ resolvers, cache, defaults })
const cache = new InMemoryCache()
const authMiddleware = new ApolloLink((operation, forward) => {
operation.setContext(context => ({
... context,
headers: {
...context.headers,
authorization: token ? `Bearer ${token}` : ''
}
}))
return forward(operation)
})
const client = new ApolloClient({
link: ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${JSON.stringify(locations)}, Path: ${path}`,
),
)
if (networkError) console.log(`[Network error]: ${networkError}`)
}),
stateLink,
concat(authMiddleware, link)
]),
cache
})
return client
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment