원격 구성 트리거


새로운 구성 버전 게시 또는 이전 버전으로 롤백을 포함한 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 함수의 예시입니다. 이 함수는 템플릿 객체의 버전 번호 필드를 검사하여 새로 업데이트된 현재 버전과 함께 버전 번호가 하나 낮은 이전 버전을 검색합니다.

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-diffrequest-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를 사용하여 템플릿 객체를 가져오기 위한 요청을 빌드하고 전송합니다.