如何解决根据 apollo 缓存中的键合并对象数组
我创建了一个辅助函数来使用 docs example 合并基于键的对象数组。它似乎工作正常,但我很好奇为什么默认情况下没有这样的辅助功能?也许有更简单的方法来做到这一点?
function mergeObjectsArray({
existing,incoming,keyFieldNames,readField,mergeObjects,}: {
existing: Record<string,string>[]
incoming: Record<string,string>[]
keyFieldNames: string[]
readField: FieldFunctionoptions['readField']
mergeObjects: FieldFunctionoptions['mergeObjects']
}) {
if (existing.length === 0) return incoming
// filter objects that's doens't have all keys
const withKeys = (item: Record<string,string>) => {
if (
// filter if key doesn't exist = !keyFieldNames.some
!keyFieldNames.some(key => {
// Return false if some key doesn't exist
if (readField(key,item)) return true
return false
})
)
return false
return true
}
const e = existing.filter(withKeys)
const i = incoming.filter(withKeys)
// create new array
const merged: Record<string,string>[] = e.slice(0)
const itemsIndex: Record<string,number> = Object.create(null)
const composeUniqueStrFromKeys = (item: Record<string,string>): string => {
const keyFields = keyFieldNames.map(key => readField(key,item))
return keyFields.join('_')
}
e.forEach((item,index) => {
itemsIndex[composeUniqueStrFromKeys(item)] = index
})
i.forEach(item => {
const composedKey = composeUniqueStrFromKeys(item)
const index = itemsIndex[composedKey]
if (typeof index === 'number') {
// Merge the new item data with the existing data.
merged[index] = mergeObjects(merged[index],item)
} else {
// First time we've seen this item in this array.
itemsIndex[composedKey] = merged.length
merged.push(item)
}
})
return merged
}
const commentBookKeyFields = ['comment_uuid','book_id']
const typePolicies: InMemoryCacheConfig['typePolicies'] = {
Query: {
fields: {
bookComments: {
keyArgs: ['where','orderBy'],merge(existing = [],incoming = [],{ readField,mergeObjects }) {
return mergeObjectsArray({ existing,keyFieldNames: commentBookKeyFields,mergeObjects })
},},CommentBook: {
keyFields: commentBookKeyFields,}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。