IBM Cloud Docs
App ConfigurationReact 客户端 SDK

App ConfigurationReact 客户端 SDK

为提高使用 "ibm-appconfiguration-react-client-sdk 的应用程序的安全性,强烈建议在 init 方法中使用加密 APIKey,而不是普通 APIKey。 这一更改对于防止用户在检查网络应用程序时暴露敏感凭据至关重要。 如果您已经在使用普通 APIKey,请更新您的应用程序,按照 此处 提到的步骤生成和使用加密 APIKey。

概述

IBM Cloud App ConfigurationReact Client SDK 用于根据IBM Cloud上的配置,在 Web 应用程序中执行功能标志和属性评估,并跟踪用于实验的自定义指标。App Configuration服务。

IBM Cloud App Configuration是集中式功能管理和配置服务 IBM Cloud 上的集中式功能管理和配置服务,适用于网络和移动应用程序、微服务以及分布式环境。 环境中使用。

使用App Configuration对您的网络应用程序进行仪表化。React Client SDK,并使用App Configuration面板、CLI 或 API 来定义功能标志或属性,将其组织成集合并针对细分市场。 在云中切换功能标志状态,以便在需要时激活或停用应用程序或环境中的功能。 运行实验,并通过跟踪自定义指标来衡量功能标志对最终用户的影响。 您还可以集中管理分布式应用程序的属性。

兼容性:SDK 与 React16.8.0及更高版本兼容。 本 SDK 以App Configuration为基础。JavaScriptClient SDK 的基础上,为 React 应用程序提供了更好的集成。 因此,"App Configuration"JavaScript客户端 SDK 的大部分功能也可供 React 客户端 SDK 使用。 阅读有关App Configuration的更多信息JavaScript客户端 SDK 的更多 信息

集成 Client 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服务的实例标识。 从App Configuration面板的服务凭据部分获取。
  • apikey: 如上所述生成的加密 APIKey '这里.
  • collectionId:在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: 实体的标识。 这将是与对功能进行求值的实体相关的字符串标识。 例如,实体可以是移动设备上运行的应用程序实例,也可以是访问网络应用程序的用户。 任何实体要与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: 实体的标识。 这将是与对属性求值的实体相关的字符串标识。 任何实体要与App Configuration 进行交互,都必须提供一个唯一的实体 ID。
  • entityAttributes: 由属性名称及其用于定义指定实体的值组成的 JSON 对象。 如果属性未配置任何目标定义,那么这是可选参数。 如果配置了目标,那么应该为规则评估提供 entityAttributes。 属性是用于定义段的参数。 SDK 使用属性值来确定指定的实体是否满足目标规则,并返回相应的属性值。

使用 React 客户端 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服务允许以下列数据类型配置功能标志和属性:布尔 数字、字符串。 字符串数据类型可以是文本字符串、JSON 或 YAML 格式。 软件开发工具包(SDK)会 对每种格式进行处理,如下表所示。

查看表
功能或属性值 DataType DataFormat Type of data returned
by getCurrentValue()
示例输出
true BOOLEAN 不适用 boolean true
25 NUMERIC 不适用 number 25
“字符串文本” 字符串 文本 string a string text
{
"firefox":{
"name":Firefox",
"pref_url":"about:config"
}
}
字符串 JSON JSON object {"firefox":{"name":"Firefox","pref_url":"about:config"}}
男:
--约翰-史密斯
--比尔-琼斯
女:"
--玛丽-史密斯
--苏珊-威廉姆斯
字符串 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许可发布。 许可证全文可在 许可证

侦听功能部件或属性更改

SDK 自动预订基于事件的机制,并在功能部件标志或属性的配置更改时重新呈现包含的组件。