在升级到 Apollo 客户端 3.3 时,我们决定启用缓存以减少网络流量并节省计算能力。我们试图实现这样的东西:
cache: new InMemoryCache({ typePolicies: {
VegaSpecification: {
keyFields: ["reportID"]
},
Query: {
fields: {
report: {
merge: true
}
}
} } })
但是,在 Apollo 中实现的缓存不适合我们的数据结构,因此我们收到不正确的结果。
首先,我们使用过滤器 a 查询报告。我们在缓存中没有该查询的任何数据,因此我们点击后端并接收
{
_id: "initialReportId",
vegaspecification: {
reportID: "initialReportId",
data: "data for a"
}
}
在缓存中 apollo 自动存储:
Report: {
_id: "initialReportId",
vegaspecification: {
"__ref":"VegaSpecification: {"reportID":"initialReportId"}"
}
}
VegaSpecification: {
reportID: "initialReportId",
data: "data for a"
}
然后我们使用过滤器 b 查询报告。我们再次在缓存中没有该查询的数据,然后点击后端并接收
{
_id: "initialReportId",
vegaspecification: {
reportID: "initialReportId",
data: "data for b"
}
}
在缓存中我们更新
Report: {
_id: "initialReportId",
vegaspecification: {
"__ref":"VegaSpecification:{"reportID":"initialReportId"}"
}
}
VegaSpecification: {
reportID: "initialReportId",
data: "data for b"
}
当我们再次查询过滤器 a 的报告时,将访问缓存,因为已经存在一个查询:
Report: {
_id: "initialReportId",
vegaspecification: {
"__ref":"VegaSpecification:{"reportID":"initialReportId"}"
}
}
然后解决对 VegaSpecification 的引用 - 返回
VegaSpecification: {
reportID: "initialReportId",
data: "data for b"
}
因此,我们为过滤器 a 返回了不正确的数据。我们使用“useMemo”来重新计算记忆值。
我们如何构造我们的实体,以便对于具有不同查询变量的不同查询,我们收到可以通过 id 区分的结果