【问题标题】:Apollo - Updating cache when some fields in some results are missingApollo - 当某些结果中的某些字段丢失时更新缓存
【发布时间】:2021-01-15 20:42:42
【问题描述】:

对于以下查询,在results 数组中的一些 对象中,某些请求的字段可能不会出现在响应中(例如photoaddress),这导致我的useQuerydataundefined(没有任何错误或警告)。

people(xyz: { q: $q, offset: $offset, rows: $rows }) {
  results {
    uri          <--- this is a field of type ID!
    name
    photo
    address {
      city
      country
    }
  }
}

我的解决方法是专门检查传入数据中是否存在该字段并提供后备值,即:将Person 的类型策略传递为{keyFields: false},并在merge 函数中执行此操作:

newItem = {...item};
newItem.photo = item.photo ?? null;
newItem.address = item.address ?? {city: "", country: ""};

之所以必须这样做是因为Person 类型中没有id 字段(相反,uri 的类型是ID!)?

我可以更好地处理这个问题吗?

【问题讨论】:

    标签: graphql apollo missing-data apollo-client typepolicies


    【解决方案1】:

    找到了更好的方法on Apollo GraphQL's GitHub

    我仍然希望有一个解决方案,我不必依次检查每种类型的可为空字段(如果有的话)。

    function nullable() {
      // Create a generic field policy that allows any field to be null by default:
      return {
        read(existing = null) {
          return existing;
        },
      };
    }
    
    new InMemoryCache({
      typePolicies: {
        Person: {
          fields: {
            photo: nullable(),
            address: nullable(),
          },
        },
        Address: { // If there's the case of either city or country missing
          fields: {
            city: nullable(), 
            country: nullable(),
          }
        }
      },
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2012-04-29
      • 2016-03-07
      • 1970-01-01
      • 2012-06-07
      • 2023-04-09
      • 2011-11-29
      相关资源
      最近更新 更多