首页 > 解决方案 > 这个谷歌云功能会导致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'});应该再次触发该函数,从而导致无限循环。

如果是这样,为什么文档不提到这一点?

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

解决方案


看起来这个特定的函数会导致一个无限循环。由于它正在侦听 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;
});

您还可以查看此相关问题以了解要采取的不同方法。


推荐阅读