Created
January 27, 2020 03:23
-
-
Save hyochan/6328ce26baefc2acb2b53d77709bd749 to your computer and use it in GitHub Desktop.
Grpahql apollo client for react-native
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from 'apollo-boost'; | |
import { AsyncStorage } from 'react-native'; | |
import { GRAPHQL_URL } from '../../config'; | |
import { WebSocketLink } from 'apollo-link-ws'; | |
import { getMainDefinition } from 'apollo-utilities'; | |
import { onError } from 'apollo-link-error'; | |
import { setContext } from 'apollo-link-context'; | |
import { split } from 'apollo-link'; | |
const httpLink = new HttpLink({ | |
uri: `${GRAPHQL_URL}`, | |
}); | |
const wsLink = new WebSocketLink({ | |
uri: `ws://${GRAPHQL_URL}`, | |
options: { reconnect: true }, | |
}); | |
const cache = new InMemoryCache(); | |
const authLink = setContext(async (_, { headers }) => { | |
const token = await AsyncStorage.getItem('token'); | |
return { | |
headers: { | |
...headers, | |
Authorization: token, | |
}, | |
}; | |
}); | |
const httpAuthLink = authLink.concat(httpLink); | |
const errorLink = onError(({ graphQLErrors, networkError }) => { | |
if (graphQLErrors) { | |
graphQLErrors.map(({ message, locations, path }) => | |
// eslint-disable-next-line no-console | |
console.log( | |
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`, | |
), | |
); | |
} | |
// eslint-disable-next-line no-console | |
if (networkError) console.log(`[Network error]: ${networkError}`); | |
}); | |
const link = split( | |
({ query }) => { | |
const definition = getMainDefinition(query); | |
return ( | |
definition.kind === 'OperationDefinition' && | |
definition.operation === 'subscription' | |
); | |
}, | |
wsLink, | |
httpAuthLink, | |
); | |
export default new ApolloClient({ | |
link: ApolloLink.from([ | |
errorLink, | |
link, | |
]), | |
cache, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment