App Configuration React 用戶端 SDK

為了增強使用 ibm-appconfiguration-react-client-sdk 應用程式的安全性,強烈建議在 init 方法中使用加密的 APIKey 而不是普通的 APIKey。 此變更對於防止使用者檢查您的 Web 應用程式時敏感憑證暴露至關重要。 如果您已經在使用普通 APIKey,請更新您的應用程式以按照 此處 提到的步驟產生並使用加密的 APIKey。

概觀

IBM Cloud App Configuration React Client SDK 用於在 Web 應用程式中執行功能標記和屬性評估,並根據IBM Cloud App Configuration服務上的配置追蹤實驗的自訂指標。

IBM Cloud App Configuration是 IBM Cloud 上的集中式功能管理和設定服務,用於網路和行動應用程序,微服務和分散式環境。

使用App Configuration React Client SDK 檢測您的 Web 應用程序,並使用App Configuration儀表板、CLI 或API 定義功能標誌或屬性,將其組織成集合和針對細分市場。 在雲端切換功能標誌狀態,以便在需要時啟用或停用應用程式或環境中的功能。 運行實驗並透過追蹤自訂指標來衡量功能標記對最終用戶的影響。 您也可以集中管理分散式應用程式的屬性。

相容性:此 SDK 與 React 版本16.8.0及更高版本相容。 此 SDK 基於App Configuration JavaScript客戶端 SDK 構建,可提供更好的整合以在 React 應用程式中使用。 因此,許多App Configuration JavaScript客戶端 SDK 功能也可供 React 用戶端 SDK 使用。 從此處 閱讀有關App Configuration JavaScript客戶端 SDK 的更多資訊。

整合用戶端 SDK for React

安裝

安裝 SDK。

npm install ibm-appconfiguration-react-client-sdk

起始設定 SDK

初始化 sdk 以連線到您的 App Configuration 服務實例,如下例所示。 使用 AppConfigProvider 覆蓋應用程式元件可讓您從元件階層的任何層次存取特性及內容。

import { withAppConfigProvider } from 'ibm-appconfiguration-react-client-sdk';

(async () => {
  const AppConfigProvider = await withAppConfigProvider({
    region: 'us-south',
    guid: '<guid>',
    apikey: '<encrypted_apikey>',
    collectionId: 'airlines-webapp',
    environmentId: 'dev'
  })

  ReactDOM.render(
    <AppConfigProvider>
        <YourApp />
    </AppConfigProvider>,
    document.getElementById('root')
  );
})();
  • 區域:建立 App Configuration 服務實體的區域名稱。 請參閱 此處 的支援地點清單。 例如:- us-south, au-syd 等。
  • guid:App Configuration服務的實例 ID。 從App Configuration儀表板的服務憑證部分取得它。
  • apikey:按照 此處 所述產生的加密 APIKey。
  • collectionId:在 Collections 部分下的App Configuration服務實例中建立的集合的 ID。
  • environmentId:在 「環境」 部分下的App Configuration服務實例中建立的環境的 ID。

始終使用加密的 APIKey 以避免洩漏敏感資訊。
確保使用 Client SDK 角色建立服務憑證,因為它具有適合在基於瀏覽器的應用程式中使用的最小存取權限。

使用特性及內容相關 API 的範例

請參閱下列範例,以瞭解如何使用特性相關 API。

取得單一特性

import { useFeature } from 'ibm-appconfiguration-react-client-sdk';

const feature = useFeature('featureId'); // returns undefined incase the featureId is invalid or doesn't exist

if (feature !== undefined) {
  console.log(`Feature Name ${feature.getFeatureName()} `);
  console.log(`Feature Id ${feature.getFeatureId()} `);
  console.log(`Feature Type ${feature.getFeatureDataType()} `);
  console.log(`Is feature enabled? ${feature.isEnabled()} `);
}

取得所有特性

import { useFeatures } from 'ibm-appconfiguration-react-client-sdk';

const features = useFeatures();
const feature = features['featureId'];

if (feature !== undefined) {
  console.log(`Feature Name ${feature.getFeatureName()} `);
  console.log(`Feature Id ${feature.getFeatureId()} `);
  console.log(`Feature Type ${feature.getFeatureDataType()} `);
  console.log(`Is feature enabled? ${feature.isEnabled()} `);
}

評估特性

您可以使用 feature.getCurrentValue(entityId, entityAttributes) 方法來評估特性旗標的值。 此方法會根據評估傳回其中一個「已啟用/已停用/已置換」值。 回覆值的資料類型符合特性旗標的資料類型。 傳遞唯一的 entityId 作為參數,以執行特性旗標評估。

const entityId = 'john_doe';
const entityAttributes = {
  city: 'Bangalore',
  country: 'India',
};

const feature = useFeature('featureId');
const featureValue = feature.getCurrentValue(entityId, entityAttributes);

其中:

  • entityId: 實體的 ID。 這將是與評估特性所依據的實體相關的字串 ID。 例如,實體可能是在行動裝置上執行的應用程式的實例,或是存取 Web 應用程式的使用者。 對於與App Configuration互動的任何實體,它必須提供唯一的實體 ID。
  • entityAttributes: JSON 物件,由定義指定實體的屬性名稱及其值組成。 如果特性旗標未配置任何目標定義,則這是選用參數。 如果已配置目標,則應該提供 entityAttributes 以進行規則評估。 屬性是用來定義區段的參數。 SDK 使用屬性值來判斷指定的實體是否滿足目標規則,並傳回適當的特性旗標值。

發送自訂指標

在實驗中使用 useTrack 掛鉤記錄自訂指標。

import { useTrack } from 'ibm-appconfiguration-react-client-sdk';

export default MyComponent = function () {
    const trackEvent = useTrack();
    return (
        <button onClick={() => trackEvent('clicked', 'user123')}>Buy</button>
    )
}

取得單一內容

import { useProperty } from 'ibm-appconfiguration-react-client-sdk';

const property = useProperty('propertyId'); // returns undefined incase the propertyId is invalid or doesn't exist

if (property !== undefined) {
  console.log(`Property Name ${property.getPropertyName()} `);
  console.log(`Property Id ${property.getPropertyId()} `);
  console.log(`Property Type ${property.getPropertyDataType()} `);
}

取得所有內容

import { useProperties } from 'ibm-appconfiguration-react-client-sdk';

const properties = useProperties();
const property = properties['propertyId'];

if (property !== undefined) {
  console.log(`Property Name ${property.getPropertyName()} `);
  console.log(`Property Id ${property.getPropertyId()} `);
  console.log(`Property Type ${property.getPropertyDataType()} `);
}

評估內容

使用 property.getCurrentValue(entityId, entityAttributes) 方法來評估內容的值。 此方法會根據評估傳回預設內容值或其置換值。 回覆值的資料類型符合內容的資料類型。

const entityId = 'john_doe';
const entityAttributes = {
  city: 'Bangalore',
  country: 'India',
};

const property = useProperty('propertyId');
const propertyValue = property.getCurrentValue(entityId, entityAttributes);

其中:

  • entityId: 實體的 ID。 這將是與評估內容所依據的實體相關的字串 ID。 對於與App Configuration互動的任何實體,它必須提供唯一的實體 ID。
  • entityAttributes: JSON 物件,由定義指定實體的屬性名稱及其值組成。 如果內容未配置任何目標定義,則這是選用參數。 如果已配置目標,則應該提供 entityAttributes 以進行規則評估。 屬性是用來定義區段的參數。 SDK 會使用屬性值來判斷指定的實體是否滿足目標規則,並傳回適當的內容值。

透過 React Client SDK 使用後備值

如果App Configuration發生連線錯誤,SDK 依賴記憶體中保留的最近評估的標誌值。 但是,如果記憶體中不存在先前值,建議使用者在程式碼中建立後備值,以確保順利運行。 下面的範例展示了這種後備方法。


import { useFeatures } from 'ibm-appconfiguration-react-client-sdk';

export default function App {
  const features = useFeatures();
  const defaultFlagValues = {
    'flight-booking': false
  }
  const entityId = 'john_doe';
  const entityAttributes = {
    city: 'Bangalore',
    country: 'India',
  };

  const getAppConfigurationFlags = (featureID, features) => {
    if (Object.keys(features).length === 0 && features.constructor === Object) {
      return defaultFlagValues[featureID];
    }

    return feature[featureID]
      ? feature[featureID].getCurrentValue(entityId, entityAttributes)
      : defaultFlagValues[featureID];
  };

  return getAppConfigurationFlags('flight-booking', features) ? <div>Flight Booking</div> : '';
}

支援的資料類型

App Configuration服務允許配置下列資料類型的功能標誌和屬性:布林值、數字、字串。 String 資料型別可以是文字字串、JSON 或 YAML 格式。 SDK 會依據下表所示的 格式進行相應處理,如下表所示。

檢視表格
特徵或屬性值 DataType DataFormat getCurrentValue() 傳回
的資料類型
輸出範例
true BOOLEAN 不適用 boolean true
25 數字 不適用 number 25
“字串文字” 字串 TEXT string a string text
{ 
"firefox": {
"名稱": " Firefox ",
"pref_url": "about:config"
}
}
字串 JSON JSON object {"firefox":{"name":"Firefox","pref_url":"about:config"}}
男士:
- John Smith
- Bill Jones
女士:
- Mary Smith
- Susan Williams
字串 YAML string

`"men:

  • John Smith
  • Bill Jones
    women:
  • Mary Smith
  • Susan Williams"`
功能標誌使用範例
const feature = useFeature('json-feature');
feature.getFeatureDataType(); // STRING
feature.getFeatureDataFormat(); // JSON

// Example (traversing the returned JSON)
let result = feature.getCurrentValue(entityId, entityAttributes);
console.log(result.key) // prints the value of the key

const feature = useFeature('yaml-feature');
feature.getFeatureDataType(); // STRING
feature.getFeatureDataFormat(); // YAML
feature.getCurrentValue(entityId, entityAttributes); // returns the stringified yaml (check above table)
內容用法範例
const property = useProperty('json-property');
property.getPropertyDataType(); // STRING
property.getPropertyDataFormat(); // JSON

// Example (traversing the returned JSON)
let result = property.getCurrentValue(entityId, entityAttributes);
console.log(result.key) // prints the value of the key

const property = useProperty('yaml-property');
property.getPropertyDataType(); // STRING
property.getPropertyDataFormat(); // YAML
property.getCurrentValue(entityId, entityAttributes); // returns the stringified yaml (check above table)

授權

該項目是在Apache 2.0許可證下發布的。 許可證的全文可以在 LICENSE 中找到

接聽特性或內容變更

當特性旗標或內容的配置變更時,SDK 會自動訂閱事件型機制,並重新呈現含括的元件。