英文:
Apollo Client: Is there a way to define Apollo Client type policy after the client object is created?
问题
所以一切都是从我发现两个查询使用相同的缓存ID开始的,导致查询在缓存中被覆盖。
export const ArtworkMastersQuery = gql`
query ARTWORK_MASTERS_QUERY($page: Int!, $perPage: Int) {
sessionStatus {
artworkMasters(page: $page, perPage: $perPage) {
...
}
}
}
`
响应: 链接
export const SessionStatusQuery = gql`
query SESSION_STATUS_QUERY {
sessionStatus {
adminUserId
cart {
...
}
user {
...
}
}
}
`
响应: 链接
在实例化 Apollo 客户端时设置 merge: true
修复了问题。
return new ApolloClient({
connectToDevTools: !isServer,
// 在 SSR 时禁用 forceFetch,只运行查询一次
ssrMode: isServer,
link: headersLink.concat(httpLink),
cache: new InMemoryCache({
typePolicies: {
SessionStatus: {
merge: true
}
}
}).restore(initialState || {}),
但问题是,我们实例化 apollo 的文件在多个服务之间共享。我想只为我的服务更改类型策略。
我认为复制整个文件(以及其他几个文件)只为添加一个策略可能有点过分。
是否有一种方法可以在不必复制文件的情况下完成这个操作?我尝试找到在运行时更新类型策略的方法,但没有成功。
英文:
So it all started when I found that two queries were using the same cache ID, causing the queries be overwritten in the cache.
export const ArtworkMastersQuery = gql`
query ARTWORK_MASTERS_QUERY($page: Int!, $perPage: Int) {
sessionStatus {
artworkMasters(page: $page, perPage: $perPage) {
...
}
}
}
`
Response: https://share.getcloudapp.com/4guXQ6gB
export const SessionStatusQuery = gql`
query SESSION_STATUS_QUERY {
sessionStatus {
adminUserId
cart {
...
}
user {
...
}
}
}
`
Response: https://share.getcloudapp.com/rRuzy4eb
Setting merge: true
when instantiating apollo client fixed the issue.
return new ApolloClient({
connectToDevTools: !isServer,
// disable forceFetch when SSR, run query only once
ssrMode: isServer,
link: headersLink.concat(httpLink),
cache: new InMemoryCache({
typePolicies: {
SessionStatus: {
merge: true
}
}
}).restore(initialState || {}),
But the problem is that the file where we instantiate apollo is shared among several services. I would like to change the type policy only for my service.
I believe it could be overkill to duplicate the entire file (and several others) just to add one policy.
Is there a way I can do this without having to duplicate the files? I tried to find a method to update the type policy during runtime, but no luck.
答案1
得分: 2
你可以使用 cache.policies.addTypePolicies
在以后的时间点添加/修改类型策略。
cache.policies.addTypePolicies({
SessionStatus: {
merge: true,
},
});
英文:
You can add/modify type policies at a later point in time by using cache.policies.addTypePolicies
cache.policies.addTypePolicies({
SessionStatus: {
merge: true,
},
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论