From 9ddb8d2cf191c2df9f807b769f6b33c5ad19748a Mon Sep 17 00:00:00 2001 From: Guillaume Chau Date: Tue, 19 Mar 2019 16:37:56 +0100 Subject: [PATCH] feat: support apollo client 2.5 local state features, closes #112 --- docs/guide/client-state.md | 33 ++++++++++++++++++++------------- graphql-client/src/index.js | 16 ++++++++++++++++ 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/docs/guide/client-state.md b/docs/guide/client-state.md index 5b3617b..89bab4c 100644 --- a/docs/guide/client-state.md +++ b/docs/guide/client-state.md @@ -1,28 +1,35 @@ # Client state -You can use [apollo-link-state](https://github.com/apollographql/apollo-link-state) for client-only local data with the `clientState` option of `createApolloClient`: +You can use [local state](https://www.apollographql.com/docs/react/essentials/local-state.html) for client-only local data with the related options of `createApolloClient`: ```js +import gql from 'graphql-tag' import { createApolloClient } from 'vue-cli-plugin-apollo/graphql-client' const options = { // ... - clientState: { - defaults: { - connected: false, - }, - resolvers: { - Mutation: { - connectedSet: (root, { value }, { cache }) => { - const data = { - connected: value, - } - cache.writeData({ data }) - }, + typeDefs: gql` + type Query { + connected: Boolean! + } + `, + resolvers: { + Mutation: { + connectedSet: (root, { value }, { cache }) => { + const data = { + connected: value, + } + cache.writeData({ data }) }, }, }, + onCacheInit: cache => { + cache.writeData({ + connected: false, + }) + }, +}, } const { apolloClient } = createApolloClient(options) diff --git a/graphql-client/src/index.js b/graphql-client/src/index.js index 0e79a1a..6417c43 100644 --- a/graphql-client/src/index.js +++ b/graphql-client/src/index.js @@ -42,6 +42,12 @@ export function createApolloClient ({ clientState = null, // Function returning Authorization header token getAuth = defaultGetAuth, + // Local Schema + typeDefs = undefined, + // Local Resolvers + resolvers = undefined, + // Hook called when you should write local state in the cache + onCacheInit = undefined, }) { let wsClient, authLink, stateLink const disableHttp = websocketsOnly && !ssr && wsEndpoint @@ -128,6 +134,7 @@ export function createApolloClient ({ } if (clientState) { + console.warn(`clientState is deprecated, see https://vue-cli-plugin-apollo.netlify.com/guide/client-state.html`) stateLink = withClientState({ cache, ...clientState, @@ -148,6 +155,8 @@ export function createApolloClient ({ // Apollo devtools connectToDevTools: process.env.NODE_ENV !== 'production', }), + typeDefs, + resolvers, ...apollo, }) @@ -156,6 +165,13 @@ export function createApolloClient ({ apolloClient.onResetStore(stateLink.writeDefaults) } + if (onCacheInit) { + onCacheInit(cache) + apolloClient.onResetStore(() => { + onCacheInit(cache) + }) + } + return { apolloClient, wsClient,