Created
October 11, 2018 10:53
-
-
Save avorona/2d3cb5f8eeaeb4dcba7c924863a8ee2f 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 ApolloClient from 'apollo-client'; | |
| import { HttpLink } from 'apollo-link-http'; | |
| import { ApolloLink } from 'apollo-link'; | |
| import { InMemoryCache } from 'apollo-cache-inmemory'; | |
| import { onError } from 'apollo-link-error'; | |
| import { setContext } from 'apollo-link-context'; | |
| import { onLogout } from '../containers/App/actions'; | |
| import firebase from '../firebase'; | |
| export const createClient = ({ dispatch, getState }) => { | |
| const httpLink = new HttpLink({ uri: process.env.API_URL }); | |
| const { companyName, referralLink } = getState().user; | |
| const authMiddleware = setContext(async (req, { headers }) => { | |
| let token; | |
| if (firebase.auth().currentUser) { | |
| token = await firebase.auth().currentUser.getIdToken(); | |
| } | |
| console.log(companyName, referralLink); | |
| let nextHeaders = headers; | |
| if (token) { | |
| nextHeaders = { | |
| ...headers, | |
| Authorization: `Bearer ${token}`, | |
| companyName: `${companyName || ''}`, | |
| referralLink: `${referralLink || ''}`, | |
| }; | |
| } | |
| return { | |
| headers: nextHeaders, | |
| }; | |
| }); | |
| const logoutLink = onError(({ response }) => { | |
| const error = response.errors && response.errors[0]; | |
| if (!error) { | |
| return; | |
| } | |
| // eslint-disable-next-line no-alert | |
| alert(error.message); | |
| if (error.name === 403) { | |
| firebase.auth().signOut(); | |
| dispatch(onLogout()); | |
| } else if (error.name === 401) { | |
| dispatch(onLogout()); | |
| } | |
| }); | |
| const link = ApolloLink.from([logoutLink, authMiddleware, httpLink]); | |
| return new ApolloClient({ | |
| link, | |
| cache: new InMemoryCache(), | |
| connectToDevTools: process.env.NODE_ENV === 'development', | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment