您可以触发一个函数来响应 Firebase Remote Config 事件(包括发布新的配置版本或回滚到旧版本)。本指南介绍如何创建 Remote Config 后台函数,以便对两个模板版本执行差异比较。
触发 Remote Config 函数
如需触发 Remote Config 函数,请先导入所需的模块:
// The Cloud Functions for Firebase SDK to set up triggers and logging.
const {onConfigUpdated} = require("firebase-functions/v2/remoteConfig");
const logger = require("firebase-functions/logger");
// The Firebase Admin SDK to obtain access tokens.
const admin = require("firebase-admin");
const app = admin.initializeApp();
const fetch = require("node-fetch");
const jsonDiff = require("json-diff");
# The Cloud Functions for Firebase SDK to set up triggers and logging.
from firebase_functions import remote_config_fn
# The Firebase Admin SDK to obtain access tokens.
import firebase_admin
app = firebase_admin.initialize_app()
import deepdiff
import requests
然后,为更新事件定义处理程序。传递给此函数的事件对象包含模板更新的相关元数据,例如新版本号和更新时间。您还可以检索执行更新的用户的电子邮件地址,以及姓名和图片(如果有)。
下面是一个 Remote Config 函数示例,该函数会记录每个更新版本与所替换掉的版本之间的差异。该函数会检查模板对象的版本号字段,并检索当前版本(最近更新版本)以及前一个版本:
exports.showconfigdiff = onConfigUpdated(async (event) => {
try {
// Obtain the access token from the Admin SDK
const accessTokenObj = await admin.credential.applicationDefault()
.getAccessToken();
const accessToken = accessTokenObj.access_token;
// Get the version number from the event object
const remoteConfigApi = "https://firebaseremoteconfig.googleapis.com/v1/" +
`projects/${app.options.projectId}/remoteConfig`;
const currentVersion = event.data.versionNumber;
const prevVersion = currentVersion - 1;
const templatePromises = [];
templatePromises.push(fetch(
remoteConfigApi,
{
method: "POST",
body: new URLSearchParams([["versionNumber", currentVersion + ""]]),
headers: {Authorization: "Bearer " + accessToken},
},
));
templatePromises.push(fetch(
remoteConfigApi,
{
method: "POST",
body: new URLSearchParams([["versionNumber", prevVersion + ""]]),
headers: {Authorization: "Bearer " + accessToken},
},
));
// Get the templates
const responses = await Promise.all(templatePromises);
const results = responses.map((r) => r.json());
const currentTemplate = results[0];
const previousTemplate = results[1];
// Figure out the differences of the templates
const diff = jsonDiff.diffString(previousTemplate, currentTemplate);
// Log the difference
logger.log(diff);
} catch (error) {
logger.error(error);
}
});
此示例使用 json-diff
和 request-promise
模块来创建差异比较并构建获取模板对象的请求。
@remote_config_fn.on_config_updated()
def showconfigdiff(event: remote_config_fn.CloudEvent[remote_config_fn.ConfigUpdateData]) -> None:
"""Log the diff of the most recent Remote Config template change."""
# Obtain an access token from the Admin SDK
access_token = app.credential.get_access_token().access_token
# Get the version number from the event object
current_version = int(event.data.version_number)
# Figure out the differences between templates
remote_config_api = ("https://firebaseremoteconfig.googleapis.com/v1/"
f"projects/{app.project_id}/remoteConfig")
current_template = requests.get(remote_config_api,
params={"versionNumber": current_version},
headers={"Authorization": f"Bearer {access_token}"})
previous_template = requests.get(remote_config_api,
params={"versionNumber": current_version - 1},
headers={"Authorization": f"Bearer {access_token}"})
diff = deepdiff.DeepDiff(previous_template, current_template)
# Log the difference
print(diff.pretty())
此示例使用 deepdiff
创建差异比较,并使用 requests
构建和发送请求以获取模板对象。