IBM Cloud Docs
针对 Node 的 App Configuration 服务器 SDK

针对 Node 的 App Configuration 服务器 SDK

App Configuration 服务提供 SDK 以与 Node.js 微服务或应用程序集成。

V v0.4.0 对 getCurrentValue 方法的返回值进行了更改。 因此,如果您已在使用低于 v0.4.0的版本,请先阅读 迁移指南,然后再将 SDK 升级到最新版本。

集成 Node 的服务器 SDK

App Configuration 服务提供 SDK 以与 Node.js 微服务或应用程序集成。 您可以通过集成 App Configuration SDK 来评估功能部件标志和属性的值。

  1. 安装 SDK。 使用 npm 注册表中的以下代码。

    npm install ibm-appconfiguration-node-sdk@latest
    
  2. 在 Node.js 微服务中,包含具有以下内容的 SDK 模块:

    const {
      AppConfiguration
    } = require('ibm-appconfiguration-node-sdk');
    
  3. 初始化 sdk 以与 App Configuration 服务实例连接。

    
    const { AppConfiguration } = require('ibm-appconfiguration-node-sdk');
    const appConfigClient = AppConfiguration.getInstance();
    
    const region = '<region>';
    const guid = '<guid>';
    const apikey = '<apikey>';
    const collectionId = 'airlines-webapp';
    const environmentId = 'dev';
    
    async function initialiseAppConfig() {
       appConfigClient.setDebug(true); // optional. (remove if not needed)
       appConfigClient.init(region, guid, apikey);
       await appConfigClient.setContext(collectionId, environmentId);
    }
    
    try {
    await initialiseAppConfig();
    console.log("app configuration sdk init successful");
    } catch (e) {
    console.error("failed to initialise app configuration sdk", e);
    }
    

    其中:

    • region:创建 App Configuration 服务实例的区域名称。 点击此处 查看支持的地点列表。 例如:- us-south, au-syd 等。
    • guid: App Configuration 服务的实例标识。 从 App Configuration 仪表板的服务凭证部分获取。
    • apikey: App Configuration 服务的 ApiKey。 从 App Configuration 仪表板的服务凭证部分获取。
    • collectionId: 在“集合”部分下的 App Configuration 服务实例中创建的集合的标识。
    • environmentId: 在“环境”部分下的 App Configuration 服务实例中创建的环境的标识。

    init()setContext() 是初始化方法,需要 仅一次 使用 appConfigClient 启动。 初始化后,可以使用 AppConfiguration.getInstance() 跨模块获取 appConfigClient

使用专用端点

(可选) 通过使用仅可通过 IBM Cloud 专用网络访问的专用端点,设置 SDK 以连接到 App Configuration 服务。

appConfigClient.usePrivateEndpoint(true);

必须先完成此操作,然后才能在 SDK 上调用 init 函数。

用于将持久高速缓存用于配置的选项

为了使应用程序和 SDK 在应用程序重新启动期间 App Configuration 服务不太可能不可用的情况下继续其操作,您可以将 SDK 配置为使用持久高速缓存。 SDK 使用持久高速缓存来存储在应用程序重新启动期间可用的 App Configuration 数据。

// 1. default (without persistent cache)
appConfigClient.setContext(collectionId, environmentId)

// 2. optional (with persistent cache)
appConfigClient.setContext(collectionId, environmentId, {
  persistentCacheDirectory: '/var/lib/docker/volumes/'
})

其中:

  • persistentCacheDirectory: 目录的绝对路径,该目录对用户具有读写许可权。 SDK 在指定目录中创建文件 appconfiguration.json,并将其用作持久高速缓存以存储 App Configuration 服务信息。

    启用持久高速缓存时,SDK 会在持久高速缓存中保留最后一个已知的良好配置。 如果无法访问 App Configuration 服务器,那么会将持久高速缓存中的最新配置装入到应用程序以继续工作。

确保在任何情况下都不会丢失或删除高速缓存文件。 例如,请考虑重新启动 Kubernetes pod 并且将高速缓存文件 (appconfiguration.json) 存储在 pod 的临时卷中的情况。 当 pod 重新启动时,Kubernetes 会破坏 pod 中的 ephermal 卷,从而删除高速缓存文件。 因此,通过提供持久目录的正确绝对路径,确保 SDK 创建的高速缓存文件始终存储在持久卷中。

脱机选项

SDK 还旨在提供配置,执行功能标志和属性评估,而无需连接到 App Configuration 服务。

appConfigClient.setContext(collectionId, environmentId, {
   bootstrapFile: 'saflights/flights.json',
   liveConfigUpdateEnabled: false
})

其中:

  • bootstrapFile: JSON 文件的绝对路径,其中包含配置详细信息。 请确保提供正确的 JSON 文件。 您可以使用 IBM Cloud App Configuration CLI 的 ibmcloud ac export 命令来生成此文件。
  • liveConfigUpdateEnabled: 从服务器进行实时配置更新。 如果不从服务器访存新配置值,请将此值设置为 false

使用与功能部件和属性相关的 API 的示例

请参阅以下示例以了解如何使用与功能部件相关的 API。

获取单一功能

const feature = appConfigClient.getFeature('feature_id'); // feature can be null incase of an invalid feature id

if (feature !== null) {
   console.log(`Feature Name ${feature.getFeatureName()} `);
   console.log(`Feature Id ${feature.getFeatureId()} `);
   console.log(`Feature Type ${feature.getFeatureDataType()} `);
   if (feature.isEnabled()) {
      // feature flag is enabled
   } else {
      // feature flag is disabled
   }
}

获取所有功能

const features = appConfigClient.getFeatures();
const feature = features['feature_id'];

if (feature !== null) {
   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) 方法来评估功能标志的值。 此方法返回一个 JSON 对象,其中包含已评估的值,已启用的功能部件标志状态和评估详细信息。

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

const result = feature.getCurrentValue(entityId, entityAttributes);
console.log(result.value); // Evaluated value of the feature flag. The type of evaluated value will match the type of feature flag (Boolean, String, Numeric).
console.log(result.isEnabled); // enabled status.
console.log(result.details); // a JSON object containing detailed information of the evaluation.

// the `result.details` will have the following
console.log(result.details.valueType); // a string value. Example: DISABLED_VALUE
console.log(result.details.reason); // a string value. Example: Disabled value of the feature flag since the feature flag is disabled.
console.log(result.details.segmentName); // (only if applicable, else it is undefined) a string value containing the segment name for which the feature flag was evaluated.
console.log(result.details.rolloutPercentageApplied); // (only if applicable, else it is undefined) a boolean value. True if the entityId was part of the rollout percentage evaluation, false otherwise.
console.log(result.details.errorType); // (only if applicable, else it is undefined) contains the error.message if any error was occured during the evaluation.
  • entityId: 实体的标识。 这是与对功能进行求值的实体相关的字符串标识。 例如,实体可能是在移动设备上运行的应用程序实例,在云上运行的微服务或运行该微服务的基础结构组件。 对于要与 App Configuration进行交互的任何实体,它必须提供唯一的实体标识。

  • entityAttributes: 由属性名称及其定义指定实体的值组成的 JSON 对象。 如果未使用任何目标定义配置功能标志,那么这是可选参数。 如果配置了目标,那么应该为规则评估提供 entityAttributes。 属性是用于定义段的参数。 SDK 使用属性值来确定指定的实体是否满足目标规则,并返回相应的功能标志值。

获取单个属性

const property = appConfigClient.getProperty('property_id'); // property can be null incase of an invalid property id

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

获取所有属性

const properties = appConfigClient.getProperties();
const property = properties['property_id'];

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

评估属性

您可以使用 property.getCurrentValue(entityId, entityAttributes) 方法来评估属性的值。 此方法返回包含求值和求值详细信息的 JSON 对象。

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

const result = property.getCurrentValue(entityId, entityAttributes);
console.log(result.value); // Evaluated value of the property. The type of evaluated value will match the type of property (Boolean, String, Numeric).
console.log(result.details); // a JSON object containing detailed information of the evaluation. See below

// the `result.details` will have the following
console.log(result.details.valueType); // a string value. Example: DEFAULT_VALUE
console.log(result.details.reason); // a string value. Example: Default value of the property.
console.log(result.details.segmentName); // (only if applicable, else it is undefined) a string value containing the segment name for which the property was evaluated.
console.log(result.details.errorType); // (only if applicable, else it is undefined) contains the error.message if any error was occured during the evaluation.
  • entityId: 实体的标识。 这是与针对其对属性求值的实体相关的字符串标识。 例如,实体可能是在移动设备上运行的应用程序实例,在云上运行的微服务或运行该微服务的基础结构组件。 对于要与 App Configuration进行交互的任何实体,它必须提供唯一的实体标识。

  • entityAttributes: 由属性名称及其定义指定实体的值组成的 JSON 对象。 如果属性未配置任何目标定义,那么这是可选参数。 如果配置了目标,那么应该为规则评估提供 entityAttributes。 属性是用于定义段的参数。 SDK 使用属性值来确定指定的实体是否满足目标规则,并返回相应的属性值。

获取私钥属性

用于获取存储在 App Configuration中的私钥引用的显式方法。

const secretPropertyObject = appConfigClient.getSecret(propertyId, secretsManagerObject);

其中,

  • propertyID: propertyID 是唯一字符串标识,通过使用此标识,您可以访存将提供必需数据来访存私钥的属性。

  • secretsManagerObject: secretsManagerObject 是用于在私钥属性求值期间获取私钥的 Secrets Manager 客户机对象。 有关如何创建 Secrets Manager 客户机对象的更多信息,请参阅 此处

评估私钥属性

使用 secretPropertyObject.getCurrentValue(entityId, entityAttributes) 方法来评估私钥属性的值。 此方法调用的输出与使用功能部件和属性对象启动的 getCurrentValue 不同。 此方法返回使用来自 Secrets Manager 的响应进行解析的 Promise,或者返回带有错误的拒绝。 解析值是求值的私钥引用的实际私钥值。 响应包含主体,头,状态码和状态文本。 如果使用 async 或 await,请使用 try 或 catch 来处理错误。

const entityId = 'john_doe';
const entityAttributes = {
   city: 'Bangalore',
   country: 'India',
};
try {
   const res = await secretPropertyObject.getCurrentValue(entityId, entityAttributes);
   console.log(JSON.stringify(res, null, 2)); // view entire response.
   console.log('Resulting secret:\n', res.result.resources[0].secret_data.payload); // the actual secret value.
} catch (err) {
   // handle the error
}

其中,

  • entityId: entityId 是与属性求值所针对的实体相关的字符串标识。 例如,实体可能是在移动设备上运行的应用程序实例,在云上运行的微服务或运行该微服务的基础结构组件。 对于要与 App Configuration进行交互的任何实体,它必须提供唯一的实体标识。

  • entityAttributes: entityAttributes 是类型为 map[string]interface{} 的映射,由属性名称及其定义指定实体的值组成。 如果属性未配置任何目标定义,那么这是可选参数。 如果配置了目标,那么应该为规则评估提供 entityAttributes。 属性是用于定义段的参数。 SDK 使用属性值来确定指定的实体是否满足目标规则,并返回相应的值。

跨其他模块访存 appConfigClient

初始化 SDK 后,可以跨其他模块获取 appConfigClient,如下所示:

// **other modules**

const { AppConfiguration } = require('ibm-appconfiguration-node-sdk');
const appConfigClient = AppConfiguration.getInstance();

feature = appConfigClient.getFeature('online-check-in');
const enabled = feature.isEnabled();
const featureValue = feature.getCurrentValue(entityId, entityAttributes)

支持的数据类型

您可以使用 App Configuration 配置功能标志和属性,支持以下数据类型:布尔、数字、SecretRef, 和字符串。 字符串数据类型可以采用文本字符串,JSON 或 YAML 的格式。 SDK 将处理表中显示的每种格式。

输出示例
功能部件或属性值 数据类型 数据格式 getCurrentValue().value 返回的数据类型 示例输出
true BOOLEAN 不适用 boolean true
25 NUMERIC 不适用 number 25
"a string text" STRING TEXT string a string text
{"firefox": {
"name": "Firefox",
"pref_url": "about:config"
}}
字符串 JSON JSONObject {"firefox":{"name":"Firefox","pref_url":"about:config"}}
men:
- John Smith
- Bill Jones
women:
- Mary Smith
- Susan Williams
STRING YAML java.lang.String

`"men:

  • John Smith
  • Bill Jones\women:
  • Mary Smith
  • Susan Williams"`

对于类型为 secret reference 的属性,请参阅自述文件部分 evaluate a secret property

功能标志

const feature = appConfigClient.getFeature('json-feature');
feature.getFeatureDataType(); // STRING
feature.getFeatureDataFormat(); // JSON

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

const feature = appConfigClient.getFeature('yaml-feature');
feature.getFeatureDataType(); // STRING
feature.getFeatureDataFormat(); // YAML
feature.getCurrentValue(entityId, entityAttributes);

属性

const property = appConfigClient.getProperty('json-property');
property.getPropertyDataType(); // STRING
property.getPropertyDataFormat(); // JSON

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

const property = appConfigClient.getProperty('yaml-property');
property.getPropertyDataType(); // STRING
property.getPropertyDataFormat(); // YAML
property.getCurrentValue(entityId, entityAttributes);

侦听功能部件或属性更改

SDK 提供了一种基于事件的机制,用于在功能标志或属性的配置发生更改时实时通知您。 您可以使用相同的 appConfigClient 来侦听 configurationUpdate 事件。

appConfigClient.emitter.on('configurationUpdate', () => {
  // **add your code**
  // To find the effect of any configuration changes, you can call the feature or property related methods

  // feature = appConfigClient.getFeature('online-check-in');
  // newResult = feature.getCurrentValue(entityId, entityAttributes);
});