@client Apollo GQL tag breaks query

眉间皱痕 提交于 2020-03-02 17:12:24

问题


I have a vue-apollo (using nuxt) query that is supposed to have a local client field show. However, when I have the show @client line included in the query the component does not render. For some reason it also seems to fail silently.

query myAccounts {
  accounts: myAccounts {
    email
    calendars {
      id
      name
      hex_color
      is_enabled
      show @client
    }
  }
}

I am extending the Calendar type in an extensions.js file (pasted below) with two mutations.

import gql from 'graphql-tag'

export const typeDefs = gql`
  extend type Calendar {
    show: Boolean
  }
  type Mutation {
    showCalendar(id: ID!): Boolean
    hideCalendar(id: ID!): Boolean
  }
`

Here is the resolver that sets the value, along with the Apollo config:

import { InMemoryCache } from 'apollo-cache-inmemory'
import { typeDefs } from './extensions'
import MY_ACCOUNTS_QUERY from '~/apollo/queries/MyAccounts'

const cache = new InMemoryCache()

const resolvers = {
  Mutation: {
    showCalendar: (_, { id }, { cache }) => {
      const data = cache.readQuery({ query: MY_ACCOUNTS_QUERY })
      const found = data.accounts
        .flatMap(({ calendars }) => calendars)
        .find(({ id }) => id === '1842')
      if (found) {
        found.show = true
      }
      cache.writeQuery({ query: todoItemsQuery, data })
      return true
    }
  }
}

export default context => {
  return {
    cache,
    typeDefs,
    resolvers,
    httpLinkOptions: {
      credentials: 'same-origin'
    },
  }
}

along with the nuxt config:

apollo: {
  defaultOptions: {
    $query: {
      loadingKey: 'loading',
      fetchPolicy: 'cache-and-network',
    },
  },
  errorHandler: '~/plugins/apollo-error-handler.js',
  clientConfigs: {
    default: '~/apollo/apollo-config.js'
  }
}

回答1:


Querying local state requires the state to exist (i.e. it should be initialized) or for a local resolver to be defined for the field. Apollo will run the resolver first, or check the cache directly for the value if a resolver is not defined. There's not really a good way to initialize that value since it's nested inside a remote query, so you can add a resolver:

const resolvers = {
  Calendar: {
    show: (parent) => !!parent.show,
  },
  // the rest of your resolvers
}

See the docs for additional examples and more details.



来源:https://stackoverflow.com/questions/57780294/client-apollo-gql-tag-breaks-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!