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

Apollo - Updating cache when some fields in some results are missing

对于以下查询,在 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 字段(相反,uriID! 类型)吗?

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

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