6
votes

On the Firebase docs they mention 4 types of triggers:

  • onCreate
  • onDelete
  • onUpdate
  • onWrite

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 cycle (in Cloud Functions):

  • Request to add a new message
  • Change the message fields
  • Add a new message with modified fields
  • Clients receive a "child_added" event
2

2 Answers

10
votes

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. 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.

  2. 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.

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.

0
votes

You need to use onWrite for this to work, as you are saving to the database more than once when you are using child_added.

onWrite(handler) returns functions.CloudFunction containing non-null functions.database.DeltaSnapshot

Event handler that fires every time a Firebase Realtime Database write of any kind (creation, update, or delete) occurs.

more info here: https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onWrite

Op wants to do the following:

Request to add a new message

If he wants to request a new message from the end-user then it is better done on the client side.

Change the message fields

Here he wants to change what was written inside the field, which is also usually done on the client side not in cloud functions.

Add a new message with modified fields

Here he wants to add the new message to the database (according to my analysis). Then this can be done in the cloud functions and the message can be added using set()

Clients receive a "child_added" event

then here after adding the new message to the database, he wants the client to receive the database trigger, that will be triggered with the new message. Here he can use cloud functions like onWrite() or onCreate()