Apollo - 当某些结果中的某些字段丢失时更新缓存

问题描述

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

undefined

我的解决方法是专门检查传入数据中是否存在该字段并提供回退值,即:将 people(xyz: { q: $q,offset: $offset,rows: $rows }) { results { uri <--- this is a field of type ID! name photo address { city country } } } 的类型策略传递为 Person 并在 {{1} 中执行此操作}} 功能

{keyFields: false}

必须这样做的原因是 merge 类型中没有 newItem = {...item}; newItem.photo = item.photo ?? null; newItem.address = item.address ?? {city: "",country: ""}; 字段(相反,idPerson 类型)?

我能以更好的方式处理这个问题吗?

解决方法

找到更好的方法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(),}
    }
  },})