【问题标题】:@client Apollo GQL tag breaks query@client Apollo GQL 标签中断查询
【发布时间】:2020-01-06 20:51:47
【问题描述】:

我有一个vue-apollo(使用nuxt)查询,它应该显示一个本地客户端字段。但是,当我在查询中包含 show @client 行时,组件不会呈现。由于某种原因,它似乎也默默地失败了。

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

我在 extensions.js 文件(粘贴在下面)中扩展了 Calendar 类型,其中包含两个突变。

import gql from 'graphql-tag'

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

这是设置值的解析器以及 Apollo 配置:

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'
    },
  }
}

连同nuxt 配置:

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

【问题讨论】:

  • 请编辑问题以包含您的 Apollo 客户端配置。
  • 已添加。我想知道如果缓存中没有键/值会如何失败,因为只有在发生突变时才会设置。

标签: graphql apollo apollo-client vue-apollo


【解决方案1】:

查询本地状态需要状态存在(即它应该被初始化)或为字段定义本地解析器。 Apollo 将首先运行解析器,如果未定义解析器,则直接检查缓存中的值。由于它嵌套在远程查询中,因此没有真正的初始化该值的好方法,因此您可以添加解析器:

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

有关更多示例和更多详细信息,请参阅 the docs

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 2020-06-07
    • 2016-09-02
    • 1970-01-01
    • 2020-08-01
    • 2020-02-02
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多