ทริกเกอร์การกำหนดค่าระยะไกล


คุณสามารถทริกเกอร์ฟังก์ชันเพื่อตอบสนองต่อเหตุการณ์ Firebase Remote Config ซึ่งรวมถึงการเผยแพร่การกำหนดค่าเวอร์ชันใหม่หรือการย้อนกลับเป็นเวอร์ชันเก่า คู่มือนี้จะอธิบายวิธีสร้างRemote Configฟังก์ชันพื้นหลัง ที่ดำเนินการเปรียบเทียบความแตกต่างของเทมเพลต 2 เวอร์ชัน

ทริกเกอร์ฟังก์ชัน 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 เพื่อสร้างและส่งคําขอเพื่อรับออบเจ็กต์เทมเพลต