Realtime Database Triggers

We can create Cloud Functions, which can respond to Realtime database changes to execute certain tasks. We can create a new function for Realtime Database events with functions.databaseTo specify when the function gets executed, we need to use one of the event handlers that are available to handle different database events. We also need to specify the database path to which the function will listen for events.

Given here are the events that are supported by Cloud Functions:

  • onWrite() : It triggers when data is created, destroyed, or changed in the Realtime Database
  • onCreate(): It triggers when new data is created in the Realtime Database

onUpdate(): It triggers when data is updated in the Realtime Database

onDelete(): It triggers when data is deleted from the Realtime Database

We can see the sample Realtime database function, which listens to users path in the database, and, whenever there is any change in the data of any user, it converts the name to uppercase and sets it as a sibling of the user's database. Here, we are using a wildcard {userId}, which essentially means any userId:

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp(functions.config().firebase);


export const makeUppercase = functions.database.ref('/users/{userId}')
.onWrite(event => {
// Grab the current value of what was written to the Realtime
Database.
const original = event.data.val();
console.log('Uppercasing', original);
//status is a property
const uppercase = original.name.toUpperCase();
// You must return a Promise when performing asynchronous tasks
inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database
returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
});

Here, event.data is a DeltaSnapshot. iT has a property called 'previous' that lets you check what was saved to the database before the event. The previous property returns a new DeltaSnapshot where all methods refer to the previous value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset