extraRootIds是Apollo缓存中的一个数组,用于定义根查询节点的其他ID。这些节点将始终存储在缓存中,即使它们的查询没有被触发。
在某些情况下,我们可能希望缓存响应的数据不仅仅在关键查询对象的下层,而是根据某些特定的上下文或实验条件存储在缓存中。如果我们将extraRootIds设置为某些节点的ID,这些节点的查询结果也将被存储在缓存中,并在后续查询中被重用。
以下是设置extraRootIds的示例代码:
import { InMemoryCache } from '@apollo/client';
const cache = new InMemoryCache({ typePolicies: { Query: { fields: { // 添加 extraRootIds 到根查询对象的 fields 中 posts: { // 设置 extraRootIds 为当前用户ID和所有文章ID // 这将确保所有与该用户相关的文章都存储在缓存中 keyArgs: ['userId', 'extraRootIds'], merge(existing, incoming, { args: { userId, extraRootIds } }) { const merged = existing ? existing.slice(0) : []; for (let i = 0; i < incoming.length; ++i) { merged[i] = incoming[i]; } // 对于特定的 extraRootIds,我们可以将其缓存为单独的字段 if (extraRootIds && extraRootIds.includes('featuredPosts')) { merged.featured = incoming.filter(post => post.featured); } return merged; }, }, }, }, }, });
在这个例子中,我们在posts字段的keyArgs属性中添加了extraRootIds,这意味着任何使用posts查询的查询都会将extraRootIds作为参数传递,并将其存储在缓存中。在merge函数