您可以触发函数以响应Firebase 远程配置事件,包括发布新配置版本或回滚到旧版本。本指南描述了如何创建一个 Remote Config 后台函数来执行两个模板版本的差异。
触发远程配置功能
要触发远程配置功能,请使用firebase-functions/v2/remoteConfig
子包。要以本指南中所示的方式响应模板更新,您需要使用onConfigUpdated
函数,将其与其他所需组件(例如 Firebase Admin SDK)一起导入:
// 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"); admin.initializeApp(); const fetch = require("node-fetch"); const jsonDiff = require("json-diff");
onConfigUpdated
返回的TemplateVersion
对象包含模板更新的关键元数据字段,例如版本号和更新时间。您还可以检索进行更新的用户的电子邮件,其中包含姓名和图像(如果可用)。
下面是一个远程配置函数的示例,它返回每个更新版本及其替换版本的差异。该函数检查模板对象的versionNumber
字段并检索当前(新更新的)版本以及较低的版本号:
exports.showconfigdiff = onConfigUpdated((event) => { // Obtain the access token from the admin SDK return admin.credential.applicationDefault().getAccessToken() .then((accessTokenObj) => { return accessTokenObj.access_token; }) .then((accessToken) => { // Get the version number from the event object const currentVersion = event.data.versionNumber; const templatePromises = []; templatePromises.push(getTemplate(currentVersion, accessToken)); templatePromises.push(getTemplate(currentVersion - 1, accessToken)); // Get the templates return Promise.all(templatePromises); }) .then((results) => { 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); return null; }).catch((error) => { logger.error(error); return null; }); });
此示例使用json-diff
和request-promise
模块来创建差异并构建请求以获取模板对象。对于结合了远程配置客户端逻辑和 Firebase 云消息传递的第一代功能示例,请参阅实时传播远程配置更新。