[英]Apollo - Updating cache when some fields in some results are missing
對於以下查詢,在results
數組的某些對象中,響應中可能不存在某些請求的字段(例如photo
或address
),這導致我的useQuery
的data
undefined
(沒有任何錯誤或警告) .
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
function 中執行此操作:
newItem = {...item};
newItem.photo = item.photo ?? null;
newItem.address = item.address ?? {city: "", country: ""};
必須這樣做的原因是Person
類型中沒有id
字段(相反, uri
是ID!
)?
我能以更好的方式處理這個問題嗎?
在 Apollo GraphQL 的 GitHub 上找到了更好的方法。
我仍然很感激一種解決方案,如果有的話,我不必依次對每種類型的可空字段進行 go 。
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(),
}
}
},
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.