遠端設定觸發條件


您可以觸發函式以回應 Firebase 遠端設定事件,包括發布新的設定版本,或復原至舊版本。本指南說明如何建立遠端設定背景函式,以便執行兩個範本版本的差異。

觸發遠端設定函式

如要為遠端設定事件定義處理常式,請使用 functions.remoteConfig 模組的 onUpdate() 函式。onUpdate 傳回的 TemplateVersion 物件包含範本更新的主要中繼資料欄位,例如版本號碼和更新時間。您也可以擷取更新使用者的電子郵件,並附上名稱和圖片 (如有)。

以下遠端設定函式範例會傳回每個更新版本和取代版本的差異。此函式會檢查範本物件的 versionNumber 欄位,並擷取目前 (新更新) 的版本,以及較低版本號碼:

exports.showConfigDiff = functions.remoteConfig.onUpdate(versionMetadata => {
  return admin.credential.applicationDefault().getAccessToken()
    .then(accessTokenObj => {
      return accessTokenObj.access_token;
    })
    .then(accessToken => {
      const currentVersion = versionMetadata.versionNumber;
      const templatePromises = [];
      templatePromises.push(getTemplate(currentVersion, accessToken));
      templatePromises.push(getTemplate(currentVersion - 1, accessToken));

      return Promise.all(templatePromises);
    })
    .then(results => {
      const currentTemplate = results[0];
      const previousTemplate = results[1];

      const diff = jsonDiff.diffString(previousTemplate, currentTemplate);

      functions.logger.log(diff);

      return null;
    }).catch(error => {
      functions.logger.error(error);
      return null;
    });
});

這個範例使用 json-diffrequest-promise 模組建立差異比較並建構要求,以取得範本物件。如需整合遠端設定用戶端邏輯和 Firebase 雲端通訊的範例,請參閱「即時傳播遠端設定更新」。