Last active
March 27, 2020 18:03
-
-
Save maticzav/86892448682f40e0bc9fc4d4a3acd93a to your computer and use it in GitHub Desktop.
This file contains 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 fetch from 'isomorphic-fetch' | |
import { ApolloClient } from 'apollo-client' | |
import { InMemoryCache } from 'apollo-cache-inmemory' | |
import { from, ApolloLink } from 'apollo-link' | |
import { createUploadLink } from 'apollo-upload-client' | |
let apolloClient = null | |
// Apollo server polyfill | |
if (!process.browser) { | |
global.fetch = fetch | |
} | |
function create(initialState = {}, { getToken }) { | |
const uploadLink = createUploadLink({ | |
uri: process.env.SERVER_ENDPOINT, | |
credentials: 'same-origin' | |
}) | |
const authLink = new ApolloLink((operation, forward) => { | |
const token = getToken() | |
operation.setContext(({ headers = {} }) => ({ | |
headers: { | |
Authorization: token ? `Bearer ${token}` : null, | |
...headers | |
} | |
})) | |
return forward(operation) | |
}) | |
const link = from([authLink, uploadLink]) | |
return new ApolloClient({ | |
link, | |
cache: new InMemoryCache().restore(initialState), | |
ssrMode: !process.browser | |
}) | |
} | |
export default function initApollo(initialState, options) { | |
if (!process.browser) { | |
return create(initialState, options) | |
} | |
if (!apolloClient) { | |
apolloClient = create(initialState, options) | |
} | |
return apolloClient | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment