From adc09f500073ff9c7d05912e7e4788ba03f16247 Mon Sep 17 00:00:00 2001 From: Evan Sosenko Date: Fri, 9 Mar 2018 10:17:39 -0800 Subject: [PATCH] Add customCache to config --- README.md | 36 ++++++++++++++++++++++++++++++++++-- src/initApollo.js | 14 +++++++++++--- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 40a483d..7c1cdbb 100644 --- a/README.md +++ b/README.md @@ -42,9 +42,41 @@ Next-apollo integrates Apollo seamlessly with Next by wrapping our pages inside On initial page load, while on the server and inside `getInitialProps`, the Apollo method, `getDataFromTree`, is invoked and returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. -## Beware Of Cache +## Custom Cache -SSR will cease to function if you pass in your own Cache. It is highly suggested that you do not pass in your own Cache in the config unless you want it to drop the SSR functionality. +SSR will cease to function if you pass in your own Cache. +It is highly suggested that you do not pass in your own Cache in +the config unless you want it to drop the SSR functionality. + +Instead, to use a custom cache, pass in a `createCache` function. +For example, to use a cache with [fragment matching], + +```jsx +import { withData } from 'next-apollo' +import { HttpLink } from 'apollo-link-http' +import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory' + +import introspectionQueryResultData from './fragmentTypes' + +const createCache = () => { + const fragmentMatcher = new IntrospectionFragmentMatcher({ + introspectionQueryResultData + }) + + return new InMemoryCache({fragmentMatcher}) +} + +const config = { + link: new HttpLink({ + uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn' + }), + createCache +} + +export default withData(config) +``` + +[fragment matching]: https://www.apollographql.com/docs/react/recipes/fragment-matching.html ## Authentication diff --git a/src/initApollo.js b/src/initApollo.js index 8fd1346..3f64e37 100644 --- a/src/initApollo.js +++ b/src/initApollo.js @@ -10,13 +10,21 @@ if (!process.browser) { global.fetch = fetch } +const createDefaultCache = () => new InMemoryCache() + function create(apolloConfig, initialState) { - return new ApolloClient({ + const createCache = apolloConfig.createCache || createDefaultCache + + const config = { connectToDevTools: process.browser, ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once) - cache: new InMemoryCache().restore(initialState || {}), + cache: createCache().restore(initialState || {}), ...apolloConfig - }) + } + + delete config.createCache + + return new ApolloClient(config) } export default function initApollo(apolloConfig, initialState, headers) {