Created
October 30, 2017 15:51
-
-
Save jamesreggio/2587df603bee8dc902e5237caa93bdc0 to your computer and use it in GitHub Desktop.
Mostly complete Apollo Client 2.0 initialization code
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
| export default async (services) => { | |
| // Links. | |
| const contextLink = new ApolloLink((operation, forward) => { | |
| operation.setContext(context => update(context, { | |
| headers: { | |
| $apply: (headers = {}) => { | |
| headers = { | |
| ...headers, | |
| 'Cookie': '', | |
| }; | |
| const sessionId = ( | |
| overrideSessionId || getSessionId(services.store.getState()) | |
| ); | |
| if (sessionId) { | |
| headers = { | |
| ...headers, | |
| 'Authorization': sessionId, | |
| }; | |
| } | |
| return headers; | |
| }, | |
| }, | |
| })); | |
| return forward(operation); | |
| }); | |
| const errorLink = new ErrorLink(({response}) => { | |
| if (errorCode(response) === 'SESSION_REQUIRED') { | |
| services.store.dispatch(Session.accountRequired()); | |
| response.errors = null; | |
| } | |
| }); | |
| const httpLink = enableApolloBatching | |
| ? new BatchHttpLink({uri: apiUri}) | |
| : new HttpLink({uri: apiUri}); | |
| const link = ApolloLink.from([contextLink, errorLink, httpLink]); | |
| // Cache. | |
| const fragmentMatcher = new IntrospectionFragmentMatcher({ | |
| introspectionQueryResultData: schema.data, | |
| }); | |
| const cache = services.cache = new InMemoryCache({ | |
| fragmentMatcher, | |
| addTypename: true, | |
| dataIdFromObject: getId, | |
| customResolvers: { | |
| Query: { | |
| node: (_, {id}) => toIdValue(id), | |
| }, | |
| }, | |
| }); | |
| // Persistence. | |
| const cacheKey = `${services.key}:apollo:2`; | |
| cache.persist = () => persistCache(cacheKey, cache); | |
| if (!purgeCache) { | |
| await restoreCache(cacheKey, cache); | |
| } | |
| // Client. | |
| services.client = new ApolloClient({link, cache}); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment