适用于所有文档的通用 Firestore 触发器

Dav*_*son 3 triggers firebase google-cloud-functions google-cloud-firestore

如何在 Firestore 中的任何集合中的任何文档更改时触发函数?我想管理createdAtupdatedAt时间戳。我有很多集合,不想为每个集合单独注册触发器。在这一点上我还不如直接创建包装函数addsetupdate

如何注册在修改任何文档时触发的回调?

编辑:

这个时候(2019-08-22),我决定只创建一个包装函数来实现这个功能。接受的答案不保持无模式。基于这篇文章,我创建了这个upset函数来管理时间戳并避免“文档不存在”错误:

const { firestore: { FieldValue } } = require('firebase-admin')

module.exports = async function upset (doc, data = {}) {
  const time = FieldValue.serverTimestamp()

  const update = { updatedAt: time }
  const updated = { ...data, ...update }

  try {
    const snapshot = await doc.get()

    if (snapshot.exists) {
      return doc.update(updated)
    } else {
      const create = { createdAt: time }
      const created = { ...updated, ...create }

      return doc.set(created)
    }
  } catch (error) {
    throw error
  }
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*nec 6

文档中所述,您可以在文档路径中使用通配符。更具体地说,“您可以定义任意数量的通配符来替换显式集合或文档 ID”

因此,以下 Cloud 函数适用于根集合下的文档:

exports.universalFirestoreTrigger = functions.firestore
    .document('{collecId}/{docId}')
    .onWrite((snap, context) => {

        console.log("Collection: " + context.params.collecId);
        console.log("Document: " + context.params.docId);

        return null;

    });
Run Code Online (Sandbox Code Playgroud)

如果您有子集合,则需要编写另一个 Cloud Functions 函数,如下所示:

exports.universalFirestoreTriggerSubCollections = functions.firestore
    .document('{collecId}/{docId}/{subCollecId}/{subDocId}')
    .onWrite((snap, context) => {

        console.log("Collection: " + context.params.collecId);
        console.log("Document: " + context.params.docId);
        console.log("Sub-Collection: " + context.params.subCollecId);
        console.log("Sub-Collection Document: " + context.params.subDocId);

        return null;

    });
Run Code Online (Sandbox Code Playgroud)

等等,如果你有子子集合......