App Configuration React 클라이언트 SDK

' ibm-appconfiguration-react-client-sdk'을 사용하는 애플리케이션의 보안을 강화하려면 init 메서드에서 일반 APIKey 대신 암호화된 APIKey를 사용할 것을 강력히 권장합니다. 이 변경은 사용자가 웹 애플리케이션을 검사할 때 민감한 자격 증명이 노출되는 것을 방지하는 데 필수적입니다. 이미 일반 APIKey를 사용 중인 경우, 여기에 설명된 단계에 따라 암호화된 APIKey를 생성하고 사용하도록 애플리케이션을 업데이트하세요.

개요

IBM Cloud App Configuration React 클라이언트 SDK는 웹 애플리케이션에서 기능 플래그 및 속성 평가를 수행하고 IBM Cloud 서비스의 구성을 기반으로 실험을 위한 사용자 정의 지표를 추적하는 데 사용됩니다 { App Configuration 서비스.

IBM Cloud App Configuration 는 중앙 집중식 기능 관리 및 구성 서비스입니다 의 IBM Cloud 웹 및 모바일 애플리케이션, 마이크로서비스, 분산 환경에서 사용하기 위한 환경에서 사용할 수 있습니다.

App Configuration 웹 애플리케이션을 계측하세요 React 클라이언트 SDK를 사용하고 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는 여기에서 확인하세요.

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 서비스의 인스턴스 ID입니다. 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: 엔티티의 ID입니다. 기능이 평가되는 엔티티와 관련된 문자열 ID입니다. 예를 들어, 엔티티는 모바일 디바이스에서 실행되는 앱의 인스턴스이거나 웹 애플리케이션에 액세스하는 사용자일 수 있습니다. 엔티티가 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 클라이언트 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 getCurrentValue()에 의해
리턴되는 데이터의 유형
출력 예
true BOOLEAN 해당 사항 없음 boolean true
25 숫자 해당 사항 없음 number 25
"문자열 텍스트" 문자열 텍스트 string a string text
{
"firefox": {
"name": "Firefox",
"pref_url": "about:config"
}
}
문자열 JSON JSON object {"firefox":{"name":"Firefox","pref_url":"about:config"}}
men:
- John Smith
- Bill Jones
women:
- 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 라이선스에 따라 배포됩니다. 라이선스 전문은 라이선스

기능 및 특성 변경 청취

SDK는 자동으로 이벤트 기반 메커니즘에 등록하고 기능 플래그 또는 특성의 구성이 변경될 때 포함된 컴포넌트를 다시 렌더링합니다.