Firebase Realtime Database Triggers

With Cloud Functions, you can handle events in the Firebase Realtime Database with no need to update client code. Cloud Functions lets you run database operations with full administrative privileges, and ensures that each change to the database is processed individually. You can make Firebase Realtime Database changes via the Firebase Admin SDK.

In a typical lifecycle, a Firebase Realtime Database function does the following:

  1. Waits for changes to a particular database location.

  2. Triggers when an event occurs and performs its tasks.

  3. Receives a data object that contains a snapshot of the data stored in the specified document.

Event types

Functions lets you handle database events at two levels of specificity; you can listen specifically for only creation, update, or deletion events, or you can listen for any change of any kind to a path. Cloud Functions supports the following event types for the Realtime Database:

Event Type Trigger
providers/google.firebase.database/eventTypes/ref.write Triggered on any mutation event: when data is created, updated, or deleted in the Realtime Database.
providers/google.firebase.database/eventTypes/ref.create Triggered when new data is created in the Realtime Database.
providers/google.firebase.database/eventTypes/ref.update Triggered when data is updated in the Realtime Database.
providers/google.firebase.database/eventTypes/ref.delete Triggered when data is deleted from the Realtime Database.

Specifying the database path and instance

To control when and where your function should trigger, you need to specify a path, and optionally specify a database instance.

Path

Path specifications match all writes that touch a path, including writes that happen anywhere below it. If you set the path for your function as /foo/bar, it matches events at both of these locations:

 /foo/bar
 /foo/bar/baz/really/deep/path

In either case, Firebase interprets that the event occurs at /foo/bar, and the event data includes the old and new data at /foo/bar. If the event data might be large, consider using multiple functions at deeper paths instead of a single function near the root of your database. For the best performance, only request data at the deepest level possible.

You can specify a path component as a wildcard by surrounding it with curly braces; foo/{bar} matches any child of /foo. The values of these wildcard path components are available within the event.params object of your function. In this example, the value is available as event.params.bar.

Paths with wildcards can match multiple events from a single write. An insert of:

{
  "foo": {
    "hello": "world",
    "firebase": "functions"
  }
}

matches the path /foo/{bar} twice: once with "hello": "world" and again with "firebase": "functions".

Instance

When using the GCP Console, if you do not specify an instance, the function deploys to the default database instance for your project.

When using the gcloud command-line tool, the instance must be specified as part of the --trigger-resource string. Usually, the default instance name is the same as your project ID.

For example if you are deploying a function in a project with the ID my-project-id, you would use the following in your --trigger-resource string:

--trigger-resource projects/_/instances/my-project-id/refs/PATH

Event structure

When handling a Realtime Database event, the data object contains two properties that are provided in JSON object format:

  • data: a snapshot of the data taken prior to the event that triggered the function.

  • delta: a snapshot of the data taken after the event that triggered the function.

Code sample

Node.js 8/10

/**
 * Triggered by a change to a Firebase RTDB reference.
 *
 * @param {object} data The event payload.
 * @param {object} context The event metadata.
 */
exports.helloRTDB = (data, context) => {
  const triggerResource = context.resource;

  console.log(`Function triggered by change to: ${triggerResource}`);
  console.log(`Admin?: ${!!data.admin}`);
  console.log(`Delta:`);
  console.log(JSON.stringify(data.delta, null, 2));
};

Node.js 6 (Deprecated)

/**
 * Triggered by a change to a Firebase RTDB reference.
 *
 * @param {!Object} event The Cloud Functions event.
 */
exports.helloRTDB = event => {
  const triggerResource = event.resource;

  console.log(`Function triggered by change to: ${triggerResource}`);
  console.log(`Admin?: ${!!event.auth.admin}`);
  console.log(`Delta:`);
  console.log(JSON.stringify(event.delta, null, 2));
};

Python

import json
def hello_rtdb(data, context):
    """ Triggered by a change to a Firebase RTDB reference.
    Args:
        data (dict): The event payload.
        context (google.cloud.functions.Context): Metadata for the event.
    """
    trigger_resource = context.resource

    print('Function triggered by change to: %s' % trigger_resource)
    print('Admin?: %s' % data.get("admin", False))
    print('Delta:')
    print(json.dumps(data["delta"]))

Go

// Package p contains a Cloud Function triggered by a Firebase Realtime Database
// event.
package p

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/functions/metadata"
)

// RTDBEvent is the payload of a RTDB event.
type RTDBEvent struct {
	Data  interface{} `json:"data"`
	Delta interface{} `json:"delta"`
}

// HelloRTDB handles changes to a Firebase RTDB.
func HelloRTDB(ctx context.Context, e RTDBEvent) error {
	meta, err := metadata.FromContext(ctx)
	if err != nil {
		return fmt.Errorf("metadata.FromContext: %v", err)
	}
	log.Printf("Function triggered by change to: %v", meta.Resource)
	log.Printf("%+v", e)
	return nil
}

Deploying your function

The following gcloud command deploys a function that will be triggered by create events on the path /messages/{pushId}/original:

gcloud functions deploy YOUR_FUNCTION_NAME \
  --trigger-event providers/google.firebase.database/eventTypes/ref.create \
  --trigger-resource projects/_/instances/DATABASE_INSTANCE/refs/messages/{pushId}/original \
  --runtime RUNTIME
Argument Description
--trigger-event NAME The name of the event type that the function wishes to receive. In this case, it will be one of the following: write, create, update or delete.
--trigger-resource NAME The fully qualified database path to which the function will listen. This should conform to the following format: projects/_/instances/DATABASE_INSTANCE/refs/PATH.
--runtime RUNTIME The name of the runtime you are using. For a complete list, see the gcloud reference.
Was deze pagina nuttig? Laat ons weten hoe goed we u hebben geholpen:

Feedback verzenden over...

Cloud Functions Documentation