新しいバージョンの構成の公開、古いバージョンへのロールバックなどの Firebase Remote Config イベントに応答してファンクションをトリガーできます。このガイドでは、テンプレートの 2 つのバージョンの差分を調べる 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 関数の例を示します。この関数はテンプレート オブジェクトのバージョン番号フィールドを調べて、最新の(更新された)バージョンとその 1 つ前のバージョンを取得します。
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
を使用して、テンプレート オブジェクトを取得するリクエストの作成と送信を行います。