您可以觸發函式,回應 Remote Config 事件,包括發布新設定版本或回溯至舊版本。本指南說明如何建立 Remote Config 背景函式,以便執行兩個範本版本的差異比較。
觸發 Remote Config 函式
如要觸發 Remote Config 函式,請先匯入必要的模組:
Node.js
// 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");
Python
# 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 函式的範例,可記錄每個更新版本與其取代的版本之間的差異。這個函式會檢查範本物件的版本號碼欄位,並擷取目前 (新更新) 版本,以及比該版本低一個號碼的版本:
Node.js
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
模組建立差異,並建構要求以取得範本物件。
Python
@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
建構及傳送要求,以便取得範本物件。