我正在尝试通过向我的文档添加时间戳并首先从缓存中获取它们,然后仅从具有较新时间戳的数据库中获取它们来减少从 Firestore 的读取。 然而,当我运行此代码时,文档“总是”从数据库中检索。即使根据我的理解,缓存仍然是空的,缓存快照应该包含以前检索到的文档,对吗? 我做错了什么?为什么文档没有被缓存?
编辑
export const firestore = initializeFirestore(app, {localCache: persistentLocalCache({})});
。现在从缓存中检索文档。然而,这些文档也会从服务器检索——甚至两次。 我得到以下输出:
来自缓存的文档:来自缓存的 8 个文档:来自数据库的 8 个文档:来自数据库的 8 个文档: 8目标是看到:
来自缓存的文档:来自数据库的 8 个文档:0
我必须改变什么才能得到这个结果?
export const getDocs = async (query) => {
const docsData = [];
var snapshotDb = null;
try {
const snapshotCache = await getDocsFromCache(query);
if (!snapshotCache.empty) {
const latestTimestamp = getLatestTimestamp(snapshotCache.docs);
snapshotCache.docs.forEach(doc => docsData.push({ id: doc.id, ...doc.data() }));
console.log('Docs from Cache: ', snapshotCache.docs.length);
snapshotDb = await getDocsFromServer(query, where('timestamp', ">", latestTimestamp));
console.log('Docs from DB: ', snapshotDb.docs.length);
snapshotDb.docs.forEach(doc => {
if (!docsData.some(d => d.id === doc.id)) {
docsData.push({ id: doc.id, ...doc.data() });
}
});
} else {
snapshotDb = await getDocsFromServer(query);
console.log('Docs from DB: ', snapshotDb.docs.length);
snapshotDb.docs.forEach(doc => docsData.push({ id: doc.id, ...doc.data() }));
}
} catch (error) {
console.error(error);
}
return docsData;
};