首页 > 解决方案 > .set / .update 集合或文档,但仅限于本地?

问题描述

我遇到了独特的用例,其中以下功能将非常有用。

本质上,我的组件正在监听 a 中的特定更改document,我的安全规则以允许读取的方式设置,但所有写入都被禁用,因为数据库更新只能通过云功能进行,因此我正在研究文档以找出是否有可能做这样的事情。

/**
 * This update should only happen locally / offline in order to update state of components
 * that are listening to changes in this document
*/
myDocumentRef.update({ name: 'newname' });

/**
 * Then cloud function is called that performs validation and if correct
 * updates document with new data (same as one we set offline above).
 * Once that is done listening components will receive new data. If unsuccessful
 * we would set document to old data (again offline) and show error.
*/
await myCloudFunction();

因此我的问题是:是否可以在本地/离线执行该更新(并且仅更新)?这基本上是利用 firebase 作为全球存储的“乐观更新”流程。

标签: firebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


Firestore 不提供“仅限本地”更新的概念。所有的写操作都会尽快与服务器同步。如果写入最终失败,API 调用返回的承诺(如果仍在内存中)将被拒绝。如果同步在应用重启后发生,promise 就会丢失,你无法知道写入是否成功。最终失败的本地写入将在本地缓存中恢复。

相反,您需要做的是以本地侦听器可以告知写入阶段的方式写入数据,可能通过将元数据写入文档以指示该阶段,并与 Cloud Function 合作以保持最新状态.


推荐阅读