次の方法で共有


JavaScript 用 Azure App Configuration クライアント ライブラリ - バージョン 1.10.0

Azure App Configuration は、開発者がアプリケーションと機能の設定を簡単かつ安全に一元化するのに役立つマネージド サービスです。

主要なリンク:

適切なパッケージを選択する

@azure/app-configuration (このライブラリ) を使用して、次のことを行います。

  • Azure App Configuration で構成設定とスナップショットを管理する
  • 通常の構成消費の領域外で動作する詳細な読み取りを実行します

ほとんどのアプリケーションは、この低レベルのクライアント ライブラリに基づいて構築され、実行時に構成を使用するのに推奨される方法である @azure/app-configuration-provider ライブラリから開始する必要があります。 さらに次のように付け加えています。

  • キー/値マップまたは構造化 JSON オブジェクトとして構成を使用する柔軟なアクセス パターン
  • アプリ構成を宣言的に作成するためのクエリ メカニズム
  • 実行時の設定の更新
  • キャッシュ、レプリカ検出、フェイルオーバー、負荷分散による高い信頼性
  • キー コンテナーの参照の解決と自動更新
  • @microsoft/機能管理ライブラリの機能フラグの統合

詳細については、「 構成プロバイダーの概要」を参照してください。

はじめ

パッケージをインストールする

npm install @azure/app-configuration

手記:構成値のみを読み取る必要があるアプリケーションの場合は、代わりに @azure/app-configuration-provider ライブラリを使用することをお勧めします。

現在サポートされている環境

  • Node.js の LTS バージョンを する
  • Safari、Chrome、Edge、Firefox の最新バージョン。

詳細については、サポート ポリシーの を参照してください。

前提 条件

App Configuration リソースを作成する

Azure Portal または Azure CLI を使用して、Azure App Configuration リソースを作成できます。

例 (Azure CLI):

az appconfig create --name <app-configuration-resource-name> --resource-group <resource-group-name> --location eastus

クライアントを認証する

AppConfigurationClient は、サービス プリンシパル を使用するか、接続文字列を使用して認証できます。

サービス プリンシパルを使用した認証

サービス プリンシパルによる認証は、次の方法で行われます。

  • @azure/identity パッケージを使用して資格情報を作成する。
  • AppConfiguration リソースに適切な RBAC ルールを設定します。 App Configuration ロールの詳細については、参照してください。

DefaultAzureCredential 使用する

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

@azure/identity の詳細については、こちらをご覧

ソブリン クラウド

ソブリンクラウドのリソースで認証するには、audienceコンストラクターオプションでAppConfigurationClientを設定する必要があります。

import { AppConfigurationClient, KnownAppConfigAudience } from "@azure/app-configuration";
import { DefaultAzureCredential } from "@azure/identity";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.azure.cn";
// Create an AppConfigurationClient that will authenticate through AAD in the China cloud
const client = new AppConfigurationClient(endpoint, new DefaultAzureCredential(), {
  audience: KnownAppConfigAudience.AzureChina,
});

注: プロパティ audience 定義されていない場合、SDK は既定で Azure パブリック クラウドになります。

接続文字列を使用した認証

App Configuration リソースのプライマリ 接続文字列 を取得するには、次の Azure CLI コマンドを使用します。

az appconfig credential list -g <resource-group-name> -n <app-configuration-resource-name> --query "([?name=='Primary'].connectionString)[0]"

コードでは、Azure CLI から取得した 接続文字列を使用して App Configuration クライアントを作成できるようになりました。

import { AppConfigurationClient } from "@azure/app-configuration";

const connectionString = "Endpoint=https://example.azconfig.io;XXX=YYYY;YYY=ZZZZ";
const client = new AppConfigurationClient(connectionString);

主な概念

AppConfigurationClient には、ポータルの App Configuration から用語がいくつか変更されています。

  • キーと値のペアは、ConfigurationSetting オブジェクトとして表されます
  • 設定のロックとロック解除は、isReadOnly フィールドに表示され、setReadOnlyを使用して切り替えることができます。
  • スナップショットは、ConfigurationSnapshot オブジェクトとして表されます。

クライアントは単純な設計手法に従います。ConfigurationSetting は、ConfigurationSettingParam または ConfigurationSettingIdを受け取る任意のメソッドに渡すことができます。

これは、このパターンが機能することを意味します。

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const setting = await client.getConfigurationSetting({
  key: "hello",
});

setting.value = "new value!";
await client.setConfigurationSetting(setting);

// fields unrelated to just identifying the setting are simply
// ignored (for instance, the `value` field)
await client.setReadOnly(setting, true);

// delete just needs to identify the setting so other fields are
// just ignored
await client.deleteConfigurationSetting(setting);

または、たとえば、設定を再取得します。

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

let setting = await client.getConfigurationSetting({
  key: "hello",
});

// re-get the setting
setting = await client.getConfigurationSetting(setting);

2022-11-01-preview API バージョンでは、構成スナップショット (構成ストアの変更できない特定の時点のコピー) がサポートされます。 スナップショットは、スナップショット内に含まれるキーと値のペアを決定するフィルターを使用して作成でき、構成ストアの変更できない構成済みビューを作成します。 この機能により、アプリケーションは構成の一貫性のあるビューを保持でき、更新が行われた時点での読み取りによる個々の設定に対するバージョンの不一致がないことを確認できます。 たとえば、この機能を使用して、App Configuration 内に "リリース構成スナップショット" を作成できます。 以下の例 の作成とスナップショットの取得に関するセクション 参照してください。

手記: アプリケーションが構成値を取得するだけで、構成設定に対して作成、更新、または削除操作を実行する必要がない場合は、代わりに @azure/app-configuration-provider ライブラリの使用を検討してください。 プロバイダー ライブラリは、実行時に構成データを読み込むための簡略化されたエクスペリエンスと 追加機能を提供します。 Microsoft Learn の Azure App Configuration ドキュメントには、多くのコード サンプルがあります。

設定を作成して取得する

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

await client.setConfigurationSetting({
  key: "testkey",
  value: "testvalue",
  // Labels allow you to create variants of a key tailored
  // for specific use-cases like supporting multiple environments.
  // https://learn.microsoft.com/azure/azure-app-configuration/concept-key-value#label-keys
  label: "optional-label",
});

const retrievedSetting = await client.getConfigurationSetting({
  key: "testkey",
  label: "optional-label",
});

console.log("Retrieved value:", retrievedSetting.value);

スナップショットを作成する

beginCreateSnapshot は、スナップショットの作成をポーリングするポーリング者を提供します。

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const key = "testkey";
const value = "testvalue";
const label = "optional-label";

await client.addConfigurationSetting({
  key,
  value,
  label,
});

const poller = await client.beginCreateSnapshot({
  name: "testsnapshot",
  retentionPeriod: 2592000,
  filters: [{ keyFilter: key, labelFilter: label }],
});
const snapshot = await poller.pollUntilDone();

beginCreateSnapshotAndWait を使用して、ポーリングが完了した直後に作成の結果を取得することもできます。

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const key = "testkey";
const value = "testvalue";
const label = "optional-label";

const snapshot = await client.beginCreateSnapshotAndWait({
  name: "testsnapshot",
  retentionPeriod: 2592000,
  filters: [{ keyFilter: key, labelFilter: label }],
});

スナップショットを取得する

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const retrievedSnapshot = await client.getSnapshot("testsnapshot");
console.log("Retrieved snapshot:", retrievedSnapshot);

スナップショット内の ConfigurationSetting を一覧表示する

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const retrievedSnapshotSettings = await client.listConfigurationSettingsForSnapshot("testsnapshot");

for await (const setting of retrievedSnapshotSettings) {
  console.log(`Found key: ${setting.key}, label: ${setting.label}`);
}

サービスからのすべてのスナップショットを一覧表示する

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

const snapshots = await client.listSnapshots();

for await (const snapshot of snapshots) {
  console.log(`Found snapshot: ${snapshot.name}`);
}

スナップショットを回復してアーカイブする

import { DefaultAzureCredential } from "@azure/identity";
import { AppConfigurationClient } from "@azure/app-configuration";

// The endpoint for your App Configuration resource
const endpoint = "https://example.azconfig.io";
const credential = new DefaultAzureCredential();
const client = new AppConfigurationClient(endpoint, credential);

// Snapshot is in ready status
const archivedSnapshot = await client.archiveSnapshot("testsnapshot");
console.log("Snapshot updated status is:", archivedSnapshot.status);

// Snapshot is in archive status
const recoverSnapshot = await client.recoverSnapshot("testsnapshot");
console.log("Snapshot updated status is:", recoverSnapshot.status);

トラブルシューティング

伐採

ログ記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、AZURE_LOG_LEVEL 環境変数を infoに設定します。 または、setLogLevel@azure/logger を呼び出すことによって、実行時にログを有効にすることもできます。

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

ログを有効にする方法の詳細な手順については、@azure/logger パッケージのドキュメントを参照してください。

React Native のサポート

React Native では、この SDK ライブラリで使用される一部の JavaScript API がサポートされていないため、それらにポリフィルを提供する必要があります。 詳細については、React Native サンプルと Expo を参照してください。

次の手順

次のサンプルは、App Configuration を操作するさまざまな方法を示しています。

  • helloworld.ts - 構成値を取得、設定、および削除します。
  • helloworldWithLabels.ts - ラベルを使用して、ベータ版と運用環境などのシナリオの設定にディメンションを追加します。
  • optimisticConcurrencyViaEtag.ts - 誤って上書きされないように、etag を使用して値を設定します。
  • setReadOnlySample.ts - 変更を防ぐため、設定を読み取り専用としてマークします。
  • getSettingOnlyIfChanged.ts - 前回の設定から変更された場合にのみ設定を取得します。
  • listRevisions.ts - キーのリビジョンを一覧表示して、以前の値と設定された日時を確認できます。
  • secretReference.ts - SecretReference は、KeyVault シークレットとして参照する構成設定を表します。
  • snapshot.ts - 構成設定の作成、一覧表示、スナップショットのアーカイブを行います。
  • featureFlag.ts - 機能フラグは、値の特定の JSON スキーマに従う設定です。

詳細な例については、GitHub の サンプル フォルダーを参照してください。

貢献

このライブラリに投稿する場合は、コードをビルドしてテストする方法の詳細については、投稿ガイド を参照してください。

このモジュールのテストは、ライブ テストと単体テストの組み合わせであり、Azure App Configuration インスタンスを用意する必要があります。 テストを実行するには、次を実行する必要があります。

  1. pnpm install
  2. pnpm build --filter @azure/app-configuration...
  3. sdk\appconfiguration\app-configuration フォルダーに次の内容を含む .env ファイルを作成します:APPCONFIG_CONNECTION_STRING=connection string for your App Configuration instance
  4. cd sdk\appconfiguration\app-configuration
  5. npm run test

詳細については、テスト フォルダーを参照してください。