监听 Firebase Realtime Database 更改

对 Firebase Realtime Database 引用进行更改会触发此函数。它会输出更改的来源、数据和增量。

代码示例

Go

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


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

import (
	"context"
	"fmt"
	"log"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/firebase/databasedata"
	"google.golang.org/protobuf/encoding/protojson"
)

func init() {
	functions.CloudEvent("HelloRTDB", HelloRTDB)
}

// HelloRTDB handles changes to a Firebase RTDB.
func HelloRTDB(ctx context.Context, e event.Event) error {
	unmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true}

	var data databasedata.ReferenceEventData
	if err := unmarshalOptions.Unmarshal(e.Data(), &data); err != nil {
		return fmt.Errorf("Unmarshal: %w", err)
	}
	log.Printf("Function triggered by change to: %v", e.Source())
	log.Printf("Data: %+v", data.GetData())
	log.Printf("Delta: %+v", data.GetDelta())
	return nil
}

Java

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.firebase.database.v1.ReferenceEventData;
import com.google.protobuf.util.JsonFormat;
import io.cloudevents.CloudEvent;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class FirebaseRtdb implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(FirebaseRtdb.class.getName());

  @Override
  public void accept(CloudEvent event) throws Exception {
    if (event.getData() == null) {
      logger.info("No data found in event");
      return;
    }

    ReferenceEventData.Builder builder = ReferenceEventData.newBuilder();
    JsonFormat.Parser jsonParser = JsonFormat.parser().ignoringUnknownFields();
    jsonParser.merge(new String(event.getData().toBytes(), StandardCharsets.UTF_8), builder);
    ReferenceEventData data = builder.build();

    logger.info("Function triggered by change to: " + event.getSource().toString());

    if (data.hasDelta()) {
      logger.info("Delta: " + data.getDelta().toString());
    }

    if (data.hasData()) {
      logger.info("Data: " + data.getData().toString());
    }
  }
}

Node.js

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * Cloud Event Function triggered by a change to a Firebase RTDB reference.
 *
 * @param {!Object} event The Cloud Functions event.
 */
const functions = require('@google-cloud/functions-framework');

functions.cloudEvent('helloRTDB', event => {
  console.log(`Function triggered by change to: ${event.source}`);
  console.log('Data:');
  console.log(JSON.stringify(event.data.data, null, 2));
  console.log('Delta:');
  console.log(JSON.stringify(event.data.delta, null, 2));
});

Python

如需向 Cloud Run functions 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

import json

from cloudevents.http import CloudEvent
import functions_framework


@functions_framework.cloud_event
def hello_rtdb(event: CloudEvent) -> None:
    """Triggered by a change to a Firebase RTDB reference.
    Args:
        event: Cloud Event triggered by change to Firebase Real Time Database.
    """
    print(f"Function triggered by change to: {event['source']}")
    print("Data:")
    print(json.dumps(event.data["data"]))
    print("Delta:")
    print(json.dumps(event.data["delta"]))

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器