Node용 App Configuration 서버 SDK
App Configuration 서비스는 Node.js 마이크로서비스 또는 애플리케이션과 통합할 수 있도록 SDK를 제공합니다.
v0.4.0 버전에서는 getCurrentValue 메서드의 반환 값이 변경되었습니다. 따라서, 현재 v0.4.0 보다 낮은 버전을 사용하고 계신다면, SDK를 최신 버전으로 업그레이드하기 전에 마이그레이션 가이드를 읽어보시기 바랍니다.
Node용 서버 SDK 통합
App Configuration 서비스는 Node.js 마이크로서비스 또는 애플리케이션과 통합할 수 있도록 SDK를 제공합니다. App Configuration SDK를 통합하여 기능 플래그 및 특성의 값을 평가할 수 있습니다.
-
SDK를 설치합니다.
npm레지스트리에서 다음 코드를 사용하십시오.npm install ibm-appconfiguration-node-sdk@latest -
Node.js 마이크로서비스에 SDK 모듈을 포함하십시오.
const { AppConfiguration } = require('ibm-appconfiguration-node-sdk'); -
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 서비스의 인스턴스 ID. App Configuration 대시보드의 ‘서비스 자격 증명’ 섹션에서 확인하세요.apikeyApiKey: App Configuration ( 서비스). App Configuration 대시보드의 ‘서비스 자격 증명’ 섹션에서 확인하세요.collectionId: ‘ App Configuration ’ 서비스 인스턴스의 ‘컬렉션’ 섹션에 생성된 컬렉션의 ID입니다.environmentId: 환경 섹션 아래의 앱 구성 서비스 인스턴스에서 작성된 환경 ID입니다.
init()및setContext()는 초기화 메소드이며appConfigClient를 사용하여 한 번만 시작해야 합니다. 초기화된 후appConfigClient는AppConfiguration.getInstance()를 사용하여 모듈 전체에서 얻을 수 있습니다.
사설 엔드포인트 사용
선택적으로, IBM Cloud 사설 네트워크를 통해서만 액세스할 수 있는 사설 엔드포인트를 사용하여 App Configuration 서비스에 연결하도록 SDK를 설정하십시오.
appConfigClient.usePrivateEndpoint(true);
이는 SDK에서 init 함수를 호출하기 전에 수행해야 합니다.
구성을 위해 지속적 캐시를 사용하는 옵션
App Configuration 서비스가 예기치 않게 중단되어 애플리케이션이 재시작되는 상황에서도 애플리케이션과 SDK가 계속 작동할 수 있도록, 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 포드가 재시작되었을 때, 캐시 파일(appconfiguration.json)이 해당 포드의 일시적 볼륨에 저장되어 있던 경우를 생각해 봅시다. 포드가 재시작되면, Kubernetes 가 포드 내의 임시 볼륨을 삭제하므로, 결과적으로 캐시 파일도 삭제됩니다. 따라서 지속적 디렉토리의
올바른 절대 경로를 제공하여 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: 엔티티의 ID입니다. 기능이 평가되는 엔티티와 관련된 문자열 ID입니다. 예를 들어 엔티티는 모바일 디바이스에서 실행되는 앱, 클라우드에서 실행되는 마이크로서비스 또는 해당 마이크로서비스를 실행하는 인프라 컴포넌트의 인스턴스일 수 있습니다. 엔티티가 App Configuration와 상호동작하려면 고유한 엔티티 ID를 제공해야 합니다. -
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: 엔티티의 ID입니다. 특성이 평가되는 엔티티와 관련된 문자열 ID입니다. 예를 들어 엔티티는 모바일 디바이스에서 실행되는 앱, 클라우드에서 실행되는 마이크로서비스 또는 해당 마이크로서비스를 실행하는 인프라 컴포넌트의 인스턴스일 수 있습니다. 엔티티가 App Configuration와 상호동작하려면 고유한 엔티티 ID를 제공해야 합니다. -
entityAttributes: 지정된 엔티티를 정의하는 속성 이름 및 해당 값으로 구성되는 JSON 오브젝트입니다. 특성이 대상 정의로 구성되지 않은 경우 이는 선택적 매개변수입니다. 대상이 구성된 경우 규칙 평가를 위해entityAttributes를 제공해야 합니다. 속성은 세그먼트를 정의하는 데 사용되는 매개변수입니다. SDK는 속성 값을 사용하여 지정된 엔티티가 대상 지정 규칙을 충족하는지 여부를 판별하고 적절한 특성 값을 리턴합니다.
시크릿 특성 가져오기
App Configuration에 저장된 시크릿 참조를 가져오기 위한 명시적 메소드입니다.
const secretPropertyObject = appConfigClient.getSecret(propertyId, secretsManagerObject);
여기서,
-
propertyID:propertyID는 고유한 문자열 ID입니다. 이를 사용하면 시크릿을 페치하는 데 필요한 데이터를 제공하는 특성을 페치할 수 있습니다. -
secretsManagerObject:secretsManagerObject는 시크릿 특성 평가 중 시크릿을 가져오는 데 사용되는 Secrets Manager 클라이언트 오브젝트입니다. Secrets Manager 클라이언트 오브젝트를 작성하는 방법에 대한 자세한 정보는 여기를 참조하십시오.
시크릿 특성 평가
secretPropertyObject.getCurrentValue(entityId, entityAttributes) 메소드를 사용하여 시크릿 특성의 값을 평가하십시오. 이 메소드 호출의 출력은 기능 및 특성 오브젝트를 사용하여 시작된 getCurrentValue 와 다릅니다. 이 메소드는 Secrets Manager 의 응답으로 분석되거나 오류로 거부되는 Promise를 리턴합니다.
해석된 값은 평가된 시크릿 참조의 실제 시크릿 값입니다. 응답에는 본문, 헤더, 상태 코드 및 상태 텍스트가 포함됩니다. 비동기 또는 대기를 사용하는 경우, 오류 처리를 위해 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는 특성이 평가되는 엔티티와 관련된 문자열 ID입니다. 예를 들어, 엔티티는 모바일 기기에서 실행되는 애플리케이션의 인스턴스일 수도 있고, 클라우드에서 실행되는 마이크로서비스일 수도 있으며, 해당 마이크로서비스를 실행하는 인프라의 구성 요소일 수도 있습니다. 엔티티가 App Configuration와 상호동작하려면 고유한 엔티티 ID를 제공해야 합니다. -
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 를 사용하여 기능 플래그와 속성을 구성할 수 있으며, 다음 데이터 유형을 지원합니다: Boolean, Numeric, SecretRef, 및 String. 문자열 데이터 유형은 텍스트 문자열, JSON 또는 YAML 형식이 될 수 있습니다. SDK는 테이블에 표시된 대로 각 형식을 처리합니다.
| 기능 또는 특성 값 | 데이터 유형 | 데이터 형식 | getCurrentValue().value 에서 리턴된 데이터 유형 |
예제 출력 |
|---|---|---|---|---|
true |
BOOLEAN | 적용 불가능 | boolean |
true |
25 |
NUMERIC | 적용 불가능 | number |
25 |
| "문자열 텍스트" | 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 Joneswomen:- Mary Smith- Susan Williams |
STRING | YAML | java.lang.String |
`"men:
|
유형 시크릿 참조의 특성은 readme 섹션 시크릿 특성 평가 를 참조하십시오.
기능 플래그
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);
});