我可以在 Firebase 函数上实现 beforeCreate 触发器吗 [英] Can I implement beforeCreate trigger on Firebase Functions

查看:20
本文介绍了我可以在 Firebase 函数上实现 beforeCreate 触发器吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase 文档中,他们提到了 4 种类型触发器:

On the Firebase docs they mention 4 types of triggers:

  • onCreate
  • onDelete
  • onUpdate
  • onWrite

有没有办法在触发child_added"侦听器之前侦听 Cloud Functions 中添加的行并修改添加行的字段?有没有办法实现 BeforeCreate?

Is there a way to listen to added row in the Cloud Functions and modify fields of an added row before the "child_added" listeners are triggered? Is there a way to implement BeforeCreate?

Desired BeforeCreate 循环(在 Cloud Functions 中):

Desired BeforeCreate cycle (in Cloud Functions):

  • 请求添加新消息
  • 更改消息字段
  • 添加带有修改字段的新消息
  • 客户端收到child_added"事件

推荐答案

Cloud Functions 中实时数据库的所有事件写入提交后异步触发.因此,在您的函数更改数据之前,其他用户可能已经看到了数据.

All events for the Realtime Database in Cloud Functions trigger asynchronously after the write has been committed. For this reason, other users may already have seen the data before your function can change it.

要解决此问题,您需要确保数据仅写入到每个人都看到的位置它被验证/修改之后.

To solve this problem you'll want to ensure the data only gets written to the location everyone sees after it's been validated/modified.

要在新数据的侦听器可以看到之前验证/修改新数据,您有两种选择:

To validate/modify the new data before listeners to that data can see it, you have two options:

  1. 使用 HTTP 触发函数来写入数据.应用程序代码调用 HTTP 函数,该函数执行您想要的数据操作,然后将结果写入数据库.

  1. Use a HTTP triggered function for writing the data. The application code calls the HTTP function, which does the data manipulation you want, and then writes the result to the database.

让应用程序写入审核队列",它只是数据库中的一个单独位置.Cloud Function 从该队列触发,验证/修改数据,将其写入实际位置,然后将其从队列中删除.

Have the applications write to a "moderation queue", which is just a separate location in the database. The Cloud Function triggers fro this queue, validates/modifies the data, writes it to the actual location, and then deletes it from the queue.

不过,使用这两种方法,您会丢失 Firebase 实时数据库的部分透明离线行为,因此您必须做出选择.

With both of these approaches you lose parts of the transparent offline behavior of the Firebase Realtime Database though, so you'll have to choose.

这篇关于我可以在 Firebase 函数上实现 beforeCreate 触发器吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆