Firebase Remote Config 触发器

您可以触发 Cloud Run functions 函数,以响应与该函数属于同一 Google Cloud 项目的 Firebase Remote Config 中的更改。这样一来,您无需发布应用更新就能更改应用的行为和外观。

事件类型

Firebase 远程配置可以触发函数来响应 remoteconfig.update 事件。

事件类型 触发器
remoteconfig.update 在远程配置模板更新时触发。

事件结构

事件数据是作为经过转换的 remoteConfig 对象提供的。

例如:

{
  "updateType": "FORCED_UPDATE",
  "updateOrigin": "CONSOLE",
  "versionNumber": 1
}

示例代码

Node.js

/**
 * Background Function triggered by a change to a Firebase Remote Config value.
 *
 * @param {object} event The Cloud Functions event.
 */
exports.helloRemoteConfig = event => {
  console.log(`Update type: ${event.updateType}`);
  console.log(`Origin: ${event.updateOrigin}`);
  console.log(`Version: ${event.versionNumber}`);
};

Python

def hello_remote_config(data, context):
    """Triggered by a change to a Firebase Remote Config value.
    Args:
           data (dict): The event payload.
           context (google.cloud.functions.Context): Metadata for the event.
    """
    print(f'Update type: {data["updateType"]}')
    print(f'Origin: {data["updateOrigin"]}')
    print(f'Version: {data["versionNumber"]}')

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"log"
)

// A RemoteConfigEvent is an event triggered by Firebase Remote Config.
type RemoteConfigEvent struct {
	UpdateOrigin string `json:"updateOrigin"`
	UpdateType   string `json:"updateType"`
	UpdateUser   struct {
		Email    string `json:"email"`
		ImageURL string `json:"imageUrl"`
		Name     string `json:"name"`
	} `json:"updateUser"`
	VersionNumber string `json:"versionNumber"`
}

// HelloRemoteConfig handles Firebase Remote Config events.
func HelloRemoteConfig(ctx context.Context, e RemoteConfigEvent) error {
	log.Printf("Update type: %v", e.UpdateType)
	log.Printf("Origin: %v", e.UpdateOrigin)
	log.Printf("Version: %v", e.VersionNumber)
	return nil
}

Java

import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.logging.Logger;

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

  // Use GSON (https://github.com/google/gson) to parse JSON content.
  private static final Gson gson = new Gson();

  @Override
  public void accept(String json, Context context) {
    JsonObject body = gson.fromJson(json, JsonObject.class);

    if (body != null) {
      if (body.has("updateType")) {
        logger.info("Update type: " + body.get("updateType").getAsString());
      }
      if (body.has("updateOrigin")) {
        logger.info("Origin: " + body.get("updateOrigin").getAsString());
      }
      if (body.has("versionNumber")) {
        logger.info("Version: " + body.get("versionNumber").getAsString());
      }
    }
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Firebase.RemoteConfig.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace FirebaseRemoteConfig;

public class Function : ICloudEventFunction<RemoteConfigEventData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, RemoteConfigEventData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Update type: {origin}", data.UpdateType);
        _logger.LogInformation("Update origin: {origin}", data.UpdateOrigin);
        _logger.LogInformation("Version number: {version}", data.VersionNumber);

        // In this example, we don't need to perform any asynchronous operations, so the
        // method doesn't need to be declared async.
        return Task.CompletedTask;
    }
}

Ruby

require "functions_framework"

# Triggered by a change to a Firebase Remote Config value
FunctionsFramework.cloud_event "hello_remote_config" do |event|
  # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  # The Firebase event payload can be obtained from the event data.
  payload = event.data

  logger.info "Update type: #{payload['updateType']}"
  logger.info "Origin: #{payload['updateOrigin']}"
  logger.info "Version: #{payload['versionNumber']}"
end

PHP


use Google\CloudFunctions\CloudEvent;

function firebaseRemoteConfig(CloudEvent $cloudevent)
{
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');

    $data = $cloudevent->getData();

    fwrite($log, 'Update type: ' . $data['updateType'] . PHP_EOL);
    fwrite($log, 'Origin: ' . $data['updateOrigin'] . PHP_EOL);
    fwrite($log, 'Version: ' . $data['versionNumber'] . PHP_EOL);
}

部署函数

如需部署函数,您需要指定事件类型 google.firebase.remoteconfig.update

以下 gcloud 命令会部署一个由 Firebase 远程配置事件触发的函数:

gcloud functions deploy FUNCTION_NAME \
  --no-gen2 \
  --entry-point ENTRY_POINT \
  --trigger-event google.firebase.remoteconfig.update \
  --runtime RUNTIME
参数 说明
FUNCTION_NAME 您要部署的 Cloud Run functions 函数的注册名称。 这可以是源代码中函数的名称,也可以是任意字符串。如果 FUNCTION_NAME 是任意字符串,则必须添加 --entry-point 标志。
--entry-point ENTRY_POINT 源代码中函数或类的名称。可选,除非您未使用 FUNCTION_NAME 指定源代码中要在部署期间执行的函数。在这种情况下,您必须使用 --entry-point 提供可执行函数的名称。
--trigger-event google.firebase.remoteconfig.update 在发生 Firebase Remote Config 更新事件时触发函数。
--runtime RUNTIME 您使用的运行时的名称。如需完整列表,请参阅 gcloud 参考文档