firebase - 这个谷歌云功能会导致firestore触发器无限循环吗?
问题描述
我有一个云功能,可以监听 Firestore 中路径的更新
export const onUserWrite = functions.firestore.document('/path/path').onWrite(async (change) => {
if (!change.after.exists) {
return;
}
await change.after.ref.update({somedata:'data'});
return true;
});
我认为这会导致无限循环,因为这段代码await change.after.ref.update({somedata:'data'});
应该再次触发该函数,从而导致无限循环。
如果是这样,为什么文档不提到这一点?
解决方案
看起来这个特定的函数会导致一个无限循环。由于它正在侦听 Firestore 中的任何写入,因此当语句使用更改参数(即DocumentSnapshot)的(DocumentReference)属性await
更新当前文档时,它将再次执行自身。ref
Firebase Functions 存储库确实包含类似的示例函数,处理潜在无限循环的一种方法是在更新 Firestore 之前实施检查。这避免了对同一函数的无限递归调用。对于我链接的示例函数,当检测到新更改时,将更新文档,并且此特定函数通过首先检查文档属性是否设置为 true 来避免无限递归调用。
exports.moderator =
functions.database.ref('/messages/{messageId}').onWrite((change) => {
const message = change.after.val();
//If document is sanitized, skip the function
if (message && !message.sanitized) {
//...
return change.after.ref.update({
text: moderatedMessage,
sanitized: true,
moderated: message.text !== moderatedMessage,
});
//Sanitized the document, when this function runs again due to this update, it will be skipped
}
return null;
});
您还可以查看此相关问题以了解要采取的不同方法。
推荐阅读
- sql-server - SQL - 在多个日期范围内查找记录时出现问题
- python - 如果用户在选择图像之前单击取消,我如何捕获异常?
- firebase - Flutter Firesbase 返回 Null
- javascript - 在刀片条件语句中使用 Javascript 变量
- python - 数据框 - 四舍五入到 N 位小数
- powershell - 在 for-each 循环中使用选择字符串
- amazon-web-services - 识别 ECS 实例的硬编码 DNS 记录
- regex - 用于匹配/提取部分文件名的正则表达式
- python - 使用python在jinja2模板中单击按钮生成CSV文件
- r - 从三元组(obj,obj,距离/相似性)在 Julia 中创建成对距离矩阵