Firebase (Google) 云函数 - Debounce/Throttle database.onWrite() #AskFirebase

Firebase (Google) Cloud Functions - Debounce/Throttle database.onWrite() #AskFirebase

场景

我在路径 documents/${documentId}

中为每个用户存储了文档

目标

我想解析它们并在文档发生变化时更新该文档的索引

代码

import Functions from 'firebase-functions'

export writeTrigger = Functions
  .database
  .ref('/document/{documentId}')
  .onWrite(
    async event => {
      const data = event.data.val()
      const { documentId } = event.params
      // assume that updateIndex function exists
      updateIndex(documentId, data)
    }
  )

问题

在文档中输入的每个字母都会调用此函数

TLDR

throttle/debounce firebase 云函数 (database.onWrite) 的最佳方式是什么,以便它不会在每次更改时触发?

您的函数将被调用对于您指定路径中或路径下的每个更改。目前没有办法阻止这种情况。

与其将每个更改都写入数据库,不如尝试在客户端批量更改并批量写出,或者定期保存状态。

或者,给客户端一些其他方式来指示函数开始工作的时间,可能是文档中的某个字段,并只听取该字段的更改。这是一个仅在字段 done 更改时触发的事件:

export writeTrigger = Functions
  .database
  .ref('/document/{documentId}/done')
  .onWrite(...)

请务必取消设置该值,以便客户端可以指示应处理另一组更改。