Created
October 27, 2019 02:30
-
-
Save tabvn/214e3e55d81f6f109b69b8a6ed15b906 to your computer and use it in GitHub Desktop.
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 { split } from 'apollo-link'; | |
| import { HttpLink } from 'apollo-link-http'; | |
| import { WebSocketLink } from 'apollo-link-ws'; | |
| import { getMainDefinition } from 'apollo-utilities'; | |
| import {setContext} from 'apollo-link-context' | |
| import {InMemoryCache} from 'apollo-cache-inmemory' | |
| import {ApolloClient} from 'apollo-client' | |
| 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}` : '', | |
| }, | |
| } | |
| }) | |
| // Create an http link: | |
| const httpLink = new HttpLink({ | |
| uri: 'http://localhost:8080/query' | |
| }); | |
| // Create a WebSocket link: | |
| const wsLink = new WebSocketLink({ | |
| uri: `ws://localhost:8080/query`, | |
| options: { | |
| reconnect: true | |
| } | |
| }); | |
| // using the ability to split links, you can send data to each link | |
| // depending on what kind of operation is being sent | |
| const link = split( | |
| // split based on operation type | |
| ({ query }) => { | |
| const definition = getMainDefinition(query); | |
| return ( | |
| definition.kind === 'OperationDefinition' && | |
| definition.operation === 'subscription' | |
| ); | |
| }, | |
| wsLink, | |
| authLink.concat(httpLink), | |
| ); | |
| export const apolloClient = new ApolloClient({ | |
| link: link, | |
| cache: new InMemoryCache(), | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment