Share via


빠른 시작: Azure App Configuration을 사용하여 JavaScript 앱 만들기

이 빠른 시작에서는 Azure App Configuration에서 Azure App Configuration JavaScript 공급자 클라이언트 라이브러리를 사용하여 애플리케이션 설정의 스토리지 및 관리를 중앙 집중화합니다.

JavaScript용 App Configuration 공급자는 JavaScript용 Azure SDK 기반으로 빌드되며 더 풍부한 기능으로 사용하기 쉽도록 설계되었습니다. App Configuration에서 키-값에 대한 액세스를 Map 개체로 사용할 수 있습니다. 여러 레이블의 구성 컴퍼지션, 키 접두사 트리밍, Key Vault 참조의 자동 확인 등과 같은 기능을 제공합니다. 예를 들어 이 자습서에서는 Node.js 앱에서 JavaScript 공급자를 사용하는 방법을 보여 줍니다.

필수 조건

키-값 추가

App Configuration 저장소에 다음 키-값을 추가합니다. Azure Portal 또는 CLI를 사용하여 저장소에 키-값을 추가하는 방법에 대한 자세한 내용은 키-값 만들기로 이동합니다.

내용 유형
message Azure App Configuration의 메시지 비워 둡니다.
app.greeting Hello World 비워 둡니다.
app.json {"myKey":"myValue"} application/json

Node.js 콘솔 앱 만들기

이 자습서에서는 Node.js 콘솔 앱을 만들고 App Configuration 저장소에서 데이터를 로드합니다.

  1. app-configuration-quickstart라는 프로젝트에 대한 새 디렉터리를 만듭니다.

    mkdir app-configuration-quickstart
    
  2. 새로 만든 app-configuration-quickstart 디렉터리로 전환합니다.

    cd app-configuration-quickstart
    
  3. npm install 명령을 사용하여 Azure App Configuration 공급자를 설치합니다.

    npm install @azure/app-configuration-provider
    

App Configuration 저장소에 연결

다음 예에서는 Azure App Configuration에서 구성 데이터를 검색하고 이를 애플리케이션에서 활용하는 방법을 보여 줍니다. 기본적으로 키-값은 Map 개체로 로드되므로 전체 키 이름을 사용하여 각 키-값에 액세스할 수 있습니다. 그러나 애플리케이션이 구성 개체를 사용하는 경우 Azure App Configuration에서 로드된 키-값을 기반으로 구성 개체를 만드는 constructConfigurationObject 도우미 API를 사용할 수 있습니다.

app-configuration-quickstart 디렉터리에 app.js라는 파일을 만들고 각 샘플의 코드를 복사합니다.

샘플 1: 기본 선택기를 사용하여 키-값 로드

이 샘플에서는 연결 문자열을 사용하여 Azure App Configuration에 연결하고 고급 옵션을 지정하지 않고 키-값을 로드합니다. 기본적으로 레이블 없이 모든 키-값을 로드합니다.

const { load } = require("@azure/app-configuration-provider");
const connectionString = process.env.AZURE_APPCONFIG_CONNECTION_STRING;

async function run() {
    console.log("Sample 1: Load key-values with default selector");

    // Connect to Azure App Configuration using a connection string and load all key-values with null label.
    const settings = await load(connectionString);

    console.log("---Consume configuration as a Map---");
    // Find the key "message" and print its value.
    console.log('settings.get("message"):', settings.get("message"));           // settings.get("message"): Message from Azure App Configuration
    // Find the key "app.greeting" and print its value.
    console.log('settings.get("app.greeting"):', settings.get("app.greeting")); // settings.get("app.greeting"): Hello World
    // Find the key "app.json" whose value is an object.
    console.log('settings.get("app.json"):', settings.get("app.json"));         // settings.get("app.json"): { myKey: 'myValue' }

    console.log("---Consume configuration as an object---");
    // Construct configuration object from loaded key-values, by default "." is used to separate hierarchical keys.
    const config = settings.constructConfigurationObject();
    // Use dot-notation to access configuration
    console.log("config.message:", config.message);             // config.message: Message from Azure App Configuration
    console.log("config.app.greeting:", config.app.greeting);   // config.app.greeting: Hello World
    console.log("config.app.json:", config.app.json);           // config.app.json: { myKey: 'myValue' }
}

run().catch(console.error);

샘플 2: 선택기를 사용하여 특정 키-값 로드

이 샘플에서는 selectors 옵션을 지정하여 키-값의 하위 집합을 로드합니다. "app."으로 시작하는 키만 로드됩니다. 필요에 따라 각각 keyFilterlabelFilter 속성이 있는 여러 선택기를 지정할 수 있습니다.

const { load } = require("@azure/app-configuration-provider");
const connectionString = process.env.AZURE_APPCONFIG_CONNECTION_STRING;

async function run() {
    console.log("Sample 2: Load specific key-values using selectors");

    // Load a subset of keys starting with "app." prefix.
    const settings = await load(connectionString, {
        selectors: [{
            keyFilter: "app.*"
        }],
    });

    console.log("---Consume configuration as a Map---");
    // The key "message" is not loaded as it does not start with "app."
    console.log('settings.has("message"):', settings.has("message"));           // settings.has("message"): false
    // The key "app.greeting" is loaded
    console.log('settings.has("app.greeting"):', settings.has("app.greeting")); // settings.has("app.greeting"): true
    // The key "app.json" is loaded
    console.log('settings.has("app.json"):', settings.has("app.json"));         // settings.has("app.json"): true

    console.log("---Consume configuration as an object---");
    // Construct configuration object from loaded key-values
    const config = settings.constructConfigurationObject({ separator: "." });
    // Use dot-notation to access configuration
    console.log("config.message:", config.message);         // config.message: undefined
    console.log("config.app.greeting:", config.greeting);   // config.app.greeting: Hello World
    console.log("config.app.json:", config.json);           // config.app.json: { myKey: 'myValue' }
}

run().catch(console.error);

샘플 3: 키-값 로드 및 키에서 접두사 자르기

이 샘플에서는 trimKeyPrefixes 옵션을 사용하여 키-값을 로드합니다. 키-값이 로드된 후 접두사 "app."는 모든 키에서 잘립니다. 이는 특정 키 접두사로 필터링하여 애플리케이션에 특정한 구성을 로드하려고 하지만 코드가 구성에 액세스할 때마다 접두사를 전달하는 것을 원하지 않을 때 유용합니다.

const { load } = require("@azure/app-configuration-provider");
const connectionString = process.env.AZURE_APPCONFIG_CONNECTION_STRING;

async function run() {
    console.log("Sample 3: Load key-values and trim prefix from keys");

    // Load all key-values with no label, and trim "app." prefix from all keys.
    const settings = await load(connectionString, {
        selectors: [{
            keyFilter: "app.*"
        }],
        trimKeyPrefixes: ["app."]
    });

    console.log("---Consume configuration as a Map---");
    // The original key "app.greeting" is trimmed as "greeting".
    console.log('settings.get("greeting"):', settings.get("greeting")); // settings.get("greeting"): Hello World
    // The original key "app.json" is trimmed as "json".
    console.log('settings.get("json"):', settings.get("json"));         // settings.get("json"): { myKey: 'myValue' }

    console.log("---Consume configuration as an object---");
    // Construct configuration object from loaded key-values with trimmed keys.
    const config = settings.constructConfigurationObject();
    // Use dot-notation to access configuration
    console.log("config.greeting:", config.greeting);   // config.greeting: Hello World
    console.log("config.json:", config.json);           // config.json: { myKey: 'myValue' }
}

run().catch(console.error);

애플리케이션 실행

  1. AZURE_APPCONFIG_CONNECTION_STRING이라는 환경 변수를 설정하고, App Configuration 저장소에 대한 연결 문자열로 설정합니다. 명령줄에서 다음 명령을 실행합니다.

    Windows 명령 프롬프트를 사용하여 로컬로 앱을 실행하려면 다음 명령을 실행하고 <app-configuration-store-connection-string>을 앱 구성 저장소의 연결 문자열로 바꿉니다.

    setx AZURE_APPCONFIG_CONNECTION_STRING "<app-configuration-store-connection-string>"
    
  2. 다음 명령을 사용하여 환경 변수 값을 인쇄하여 올바르게 설정되었는지 유효성을 검사합니다.

    Windows 명령 프롬프트를 사용하여 명령 프롬프트를 다시 시작하여 변경 내용이 적용되도록 하고 다음 명령을 실행합니다.

    echo %AZURE_APPCONFIG_CONNECTION_STRING%
    
  3. 환경 변수가 제대로 설정되면 다음 명령을 실행하여 앱을 로컬로 실행합니다.

    node app.js
    

    각 샘플에 대해 다음 출력이 표시됩니다.

    샘플 1

    Sample 1: Load key-values with default selector
    ---Consume configuration as a Map---
    settings.get("message"): Message from Azure App Configuration
    settings.get("app.greeting"): Hello World
    settings.get("app.json"): { myKey: 'myValue' }
    ---Consume configuration as an object---
    config.message: Message from Azure App Configuration
    config.app.greeting: Hello World
    config.app.json: { myKey: 'myValue' }
    

    샘플 2

    Sample 2: Load specific key-values using selectors
    ---Consume configuration as a Map---
    settings.has("message"): false
    settings.has("app.greeting"): true
    settings.has("app.json"): true
    ---Consume configuration as an object---
    config.message: undefined
    config.app.greeting: Hello World
    config.app.json: { myKey: 'myValue' }
    

    샘플 3

    Sample 3: Load key-values and trim prefix from keys
    ---Consume configuration as a Map---
    settings.get("greeting"): Hello World
    settings.get("json"): { myKey: 'myValue' }
    ---Consume configuration as an object---
    config.greeting: Hello World
    config.json: { myKey: 'myValue' }
    

리소스 정리

이 문서에서 만든 리소스를 계속 사용하지 않으려면 여기서 만든 리소스 그룹을 삭제하여 요금이 부과되지 않도록 합니다.

Important

리소스 그룹을 삭제하면 다시 되돌릴 수 없습니다. 리소스 그룹 및 포함된 모든 리소스가 영구적으로 삭제됩니다. 잘못된 리소스 그룹 또는 리소스를 자동으로 삭제하지 않도록 합니다. 유지하려는 다른 리소스가 포함된 리소스 그룹 내에서 이 문서에 대한 리소스를 만든 경우 리소스 그룹을 삭제하는 대신 해당 창에서 각 리소스를 개별적으로 삭제합니다.

  1. Azure Portal에 로그인하고 리소스 그룹을 선택합니다.
  2. 이름으로 필터링 상자에서 리소스 그룹의 이름을 입력합니다.
  3. 결과 목록에서 리소스 그룹 이름을 선택하여 개요를 확인합니다.
  4. 리소스 그룹 삭제를 선택합니다.
  5. 리소스 그룹 삭제를 확인하는 메시지가 표시됩니다. 리소스 그룹의 이름을 입력하여 확인하고 삭제를 선택합니다.

잠시 후, 리소스 그룹 및 모든 해당 리소스가 삭제됩니다.

다음 단계

이 빠른 시작에서는 새 App Configuration 저장소를 만들고 Node.js 앱에서 App Configuration JavaScript 공급자를 사용하여 키-값에 액세스하는 방법을 알아보았습니다.

더 많은 코드 샘플을 보려면 다음을 방문하세요.