JavaScript용 Azure Tables 클라이언트 라이브러리 - 버전 13.2.2

Azure Tables 는 구조화된 NoSQL 데이터를 저장하여 스키마 없는 디자인의 키/특성 저장소를 제공하는 클라우드 기반 서비스입니다. 테이블 스토리지는 개발자에게 Azure 클라우드의 가장 좋은 부분을 통해 유연성과 확장성을 제공합니다.

클라이언트 라이브러리를 사용하여 다음을 수행할 수 있습니다.

  • 테이블 만들기/삭제
  • 엔터티 쿼리/만들기/읽기/업데이트/삭제

Azure Cosmos DB는 Azure Table Storage용으로 작성되었으며 다음과 같은 프리미엄 기능이 필요한 애플리케이션에 대한 Table API를 제공합니다.

  • 턴키 전역 배포
  • 전 세계적인 전용 처리량
  • 99번째 백분위수에서 1자리 밀리초 대기 시간
  • 보장된 고가용성
  • 자동 보조 인덱싱.
  • Azure Tables 클라이언트 라이브러리는 코드 변경 없이 Azure Table Storage 또는 Azure Cosmos DB 테이블 서비스 엔드포인트를 원활하게 대상으로 지정할 수 있습니다.

주요 링크:

시작

필수 조건

현재 지원되는 환경:

  • Node.js의 LTS 버전
  • Safari, Chrome, Edge 및 Firefox의 최신 버전

이 패키지를 사용하려면 Azure 구독스토리지 계정 또는 Azure CosmosDB 데이터베이스 가 있어야 합니다.

@azure/data-tables 패키지를 설치합니다.

JavaScript용 Azure Tables 클라이언트 라이브러리를 설치하는 기본 방법은 npm 패키지 관리자를 사용하는 것입니다. 터미널 창에 다음을 입력합니다.

npm install @azure/data-tables

인증 TableServiceClient

Azure Tables는 인증하는 여러 가지 방법을 지원합니다. Azure Tables 서비스와 상호 작용하려면 Tables 클라이언트 TableServiceClientTableClient 의 instance 만들어야 합니다. 인증에 대한 자세한 내용은 를 만들기 TableServiceClient위한 샘플을 참조하세요.

참고: AAD(Azure Active Directory)는 Azure Storage 계정에 대해서만 지원됩니다.

다음 기능, 인터페이스, 클래스 또는 함수는 Node.js

  • 계정 이름 및 계정 키를 기반으로 하는 공유 키 권한 부여
    • AzureNamedKeyCredential
    • 계정 연결 문자열입니다.

JavaScript 번들

브라우저에서 이 클라이언트 라이브러리를 사용하려면 먼저 번들러를 사용해야 합니다. 이 작업을 수행하는 방법에 대한 자세한 내용은 번들링 설명서를 참조하세요.

CORS

브라우저용으로 개발해야 하는 경우 스토리지 계정에 대해 CORS(원본 간 리소스 공유) 규칙을 설정해야 합니다. Azure Portal 이동하여 Azure Storage Explorer 스토리지 계정을 찾고 Blob/queue/file/table service에 대한 새 CORS 규칙을 만듭니다.

예를 들어 디버깅을 위해 다음 CORS 설정을 만들 수 있습니다. 하지만 프로덕션 환경의 요구 사항에 따라 설정을 신중하게 사용자 지정하세요.

  • 허용된 원본: *
  • 허용되는 동사: DELETE, GET,HEAD,MERGE,POST,OPTIONS,PUT
  • 허용되는 헤더: *
  • 노출된 헤더: *
  • 최대 연령(초): 86400

주요 개념

  • TableServiceClient - 테이블 만들기, 나열 및 삭제와 같은 테이블 서비스 수준에서 상호 작용하는 함수를 제공하는 클라이언트

  • TableClient - 테이블 내에서 엔터티 만들기, 나열 및 삭제와 같은 엔터티 수준에서 상호 작용하는 함수를 제공하는 클라이언트입니다.

  • Table - 테이블은 데이터를 엔터티 컬렉션으로 저장합니다.

  • Entity - 엔터티는 행과 유사합니다. 엔터티에는 기본 키와 속성 집합이 있습니다. 속성은 이름-형식화된 값 쌍으로, 열과 비슷합니다.

Table service의 일반적인 사용은 다음과 같습니다.

  • 웹 규모 애플리케이션을 처리할 수 있는 구조화된 데이터 TB 저장
  • 복잡한 조인, 외장 키 또는 저장 프로시저가 필요하지 않고 빠른 액세스를 위해 정규화 해제할 수 있는 데이터 세트 저장
  • 클러스터형 인덱스를 사용하여 신속하게 데이터 쿼리
  • OData 프로토콜 필터 식을 사용하여 데이터에 액세스

예제

패키지 가져오기

클라이언트를 사용하려면 파일에서 패키지를 가져옵니다.

const AzureTables = require("@azure/data-tables");

또는 필요한 형식만 선택적으로 가져옵니다.

const { TableServiceClient, AzureNamedKeyCredential } = require("@azure/data-tables");

Table service 클라이언트 만들기

TableServiceClient 에는 테이블 서비스에 대한 URL과 액세스 자격 증명이 필요합니다. 또한 필요에 따라 매개 변수의 options 일부 설정을 허용합니다.

TableServiceClient AzureNamedKeyCredential

account-name 및 account-key를 TableServiceClientAzureNamedKeyCredential 인수로 전달하여 를 로 인스턴스화할 수 있습니다. (계정 이름 및 계정 키는 Azure Portal에서 가져올 수 있습니다.) [NODE.JS 런타임에서만 사용 가능]

const { TableServiceClient, AzureNamedKeyCredential } = require("@azure/data-tables");

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new AzureNamedKeyCredential(account, accountKey);
const serviceClient = new TableServiceClient(
  `https://${account}.table.core.windows.net`,
  credential
);

TableServiceClient TokenCredential(AAD) 사용

Azure Tables는 스토리지 엔드포인트를 대상으로 할 때 Table Service에 대한 요청의 ID 기반 인증을 위해 Azure Active Directory(Azure AD)와 통합됩니다. Azure AD 사용하여 RBAC(역할 기반 액세스 제어)를 사용하여 사용자, 그룹 또는 애플리케이션에 Azure Table 리소스에 대한 액세스 권한을 부여할 수 있습니다.

를 사용하여 테이블 리소스에 TokenCredential액세스하려면 인증된 ID에 "스토리지 테이블 데이터 기여자" 또는 "스토리지 테이블 데이터 판독기" 역할이 있어야 합니다.

@azure/identity 패키지를 사용하면 개발 환경과 프로덕션 환경 모두에서 요청에 원활하게 권한을 부여할 수 있습니다. Azure Storage의 Azure AD 통합에 대한 자세한 내용은 Azure.Identity 추가 정보를 참조하세요.

const { TableServiceClient } = require("@azure/data-tables");
const { DefaultAzureCredential } = require("@azure/identity");

// DefaultAzureCredential expects the following three environment variables:
// - AZURE_TENANT_ID: The tenant ID in Azure Active Directory
// - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
// - AZURE_CLIENT_SECRET: The client secret for the registered application
const credential = new DefaultAzureCredential();
const account = "<account name>";

const clientWithAAD = new TableServiceClient(
  `https://${account}.table.core.windows.net`,
  credential
);

TableServiceClient SAS 토큰으로

또한 SAS(공유 액세스 서명)를 사용하여 를 인스턴스화 TableServiceClient 할 수 있습니다. Azure Portal에서 SAS 토큰을 가져올 수 있습니다.

const { TableServiceClient, AzureSASCredential } = require("@azure/data-tables");

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";

const serviceClientWithSAS = new TableServiceClient(
  `https://${account}.table.core.windows.net`,
  new AzureSASCredential(sas)
);

계정의 테이블 나열

함수를 호출하는 instance 통해 TableServiceClient 계정 내의 테이블을 나열할 listTables 수 있습니다. 이 함수는 를 사용하여 사용할 수 있는 를 PageableAsyncIterator 반환합니다. for-await-of

const { TableServiceClient, AzureNamedKeyCredential } = require("@azure/data-tables");

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new AzureNamedKeyCredential(account, accountKey);
const serviceClient = new TableServiceClient(
  `https://${account}.table.core.windows.net`,
  credential
);

async function main() {
  let tablesIter = serviceClient.listTables();
  let i = 1;
  for await (const table of tablesIter) {
    console.log(`Table${i}: ${table.name}`);
    i++;
    // Output:
    // Table1: testTable1
    // Table1: testTable2
    // Table1: testTable3
    // Table1: testTable4
    // Table1: testTable5
  }
}

main();

새 테이블 만들기

함수를 호출 createTable 하는 instance 통해 TableServiceClient 테이블을 만들 수 있습니다. 이 함수는 매개 변수로 만들 테이블의 이름을 사용합니다. 테이블이 createTable 이미 있을 때는 오류가 발생하지 않습니다.

const { TableServiceClient, AzureNamedKeyCredential } = require("@azure/data-tables");

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new AzureNamedKeyCredential(account, accountKey);
const serviceClient = new TableServiceClient(
  `https://${account}.table.core.windows.net`,
  credential
);

async function main() {
  const tableName = `newtable`;
  // If the table 'newTable' already exists, createTable doesn't throw
  await serviceClient.createTable(tableName);
}

main();

다음은 테이블을 만들 때 테이블이 이미 있는지 테스트하는 방법을 보여 주는 샘플입니다.

const { TableServiceClient, AzureNamedKeyCredential } = require("@azure/data-tables");

const account = "<account>";
const accountKey = "<accountkey>";

const credential = new AzureNamedKeyCredential(account, accountKey);
const serviceClient = new TableServiceClient(
  `https://${account}.table.core.windows.net`,
  credential
);

async function main() {
  const tableName = `newtable${new Date().getTime()}`;
  await serviceClient.createTable(tableName, {
    onResponse: (response) => {
      if (response.status === 409) {
        console.log(`Table ${tableName} already exists`);
      }
    }
  });
}

main();

테이블 클라이언트 만들기

TableClient 테이블 이름을 매개 변수로 TableServiceClient 사용하는 차이를 TableClient 가진 와 비슷한 방식으로 만들어집니다.

TableClient(AzureNamedKeyCredential 사용)

account-name 및 account-key를 TableClient 인수로 전달하여 를 AzureNamedKeyCredential 사용하여 를 인스턴스화할 수 있습니다. (계정 이름 및 계정 키는 Azure Portal에서 가져올 수 있습니다.) [NODE.JS 런타임에서만 사용 가능]

const { TableClient, AzureNamedKeyCredential } = require("@azure/data-tables");

// Enter your storage account name and shared key
const account = "<account>";
const accountKey = "<accountkey>";
const tableName = "<tableName>";

// Use AzureNamedKeyCredential with storage account and account key
// AzureNamedKeyCredential is only available in Node.js runtime, not in browsers
const credential = new AzureNamedKeyCredential(account, accountKey);
const client = new TableClient(`https://${account}.table.core.windows.net`, tableName, credential);

TableClient with TokenCredential (Azure Active Directory)

Azure Tables는 스토리지 엔드포인트를 대상으로 할 때 Table Service에 대한 요청의 ID 기반 인증을 위해 Azure Active Directory(Azure AD)와 통합을 제공합니다. Azure AD 사용하면 RBAC(역할 기반 액세스 제어)를 사용하여 사용자, 그룹 또는 애플리케이션에 Azure Table 리소스에 대한 액세스 권한을 부여할 수 있습니다.

를 사용하여 테이블 리소스에 TokenCredential액세스하려면 인증된 ID에 "스토리지 테이블 데이터 기여자" 또는 "스토리지 테이블 데이터 판독기" 역할이 있어야 합니다.

@azure/identity 패키지를 사용하면 개발 및 프로덕션 환경 모두에서 요청에 원활하게 권한을 부여할 수 있습니다. Azure Storage의 Azure AD 통합에 대한 자세한 내용은 Azure.Identity 추가 정보를 참조하세요.

const { TableClient } = require("@azure/data-tables");
const { DefaultAzureCredential } = require("@azure/identity");

// DefaultAzureCredential expects the following three environment variables:
// - AZURE_TENANT_ID: The tenant ID in Azure Active Directory
// - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
// - AZURE_CLIENT_SECRET: The client secret for the registered application
const credential = new DefaultAzureCredential();
const account = "<account name>";
const tableName = "<tableName>";

const clientWithAAD = new TableClient(
  `https://${account}.table.core.windows.net`,
  tableName,
  credential
);

TableClient SAS 토큰으로

SAS(공유 액세스 서명)를 사용하여 를 인스턴스화 TableClient 할 수 있습니다. Azure Portal에서 SAS 토큰을 가져올 수 있습니다.

const { TableClient, AzureSASCredential } = require("@azure/data-tables");

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const tableName = "<tableName>";

const clientWithSAS = new TableClient(
  `https://${account}.table.core.windows.net`,
  tableName,
  new AzureSASCredential(sas)
);

TableClient TokenCredential(AAD) 사용

Azure Tables는 스토리지 엔드포인트를 대상으로 할 때 Table Service에 대한 요청의 ID 기반 인증을 위해 Azure Active Directory(Azure AD)와 통합을 제공합니다. Azure AD 사용하면 RBAC(역할 기반 액세스 제어)를 사용하여 사용자, 그룹 또는 애플리케이션에 Azure Table 리소스에 대한 액세스 권한을 부여할 수 있습니다.

를 사용하여 테이블 리소스에 TokenCredential액세스하려면 인증된 ID에 "스토리지 테이블 데이터 기여자" 또는 "스토리지 테이블 데이터 판독기" 역할이 있어야 합니다.

@azure/identity 패키지를 사용하면 개발 및 프로덕션 환경 모두에서 요청에 원활하게 권한을 부여할 수 있습니다. Azure Storage의 Azure AD 통합에 대한 자세한 내용은 Azure.Identity 추가 정보를 참조하세요.

const { TableClient } = require("@azure/data-tables");
const { DefaultAzureCredential } = require("@azure/identity");

// DefaultAzureCredential expects the following three environment variables:
// - AZURE_TENANT_ID: The tenant ID in Azure Active Directory
// - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
// - AZURE_CLIENT_SECRET: The client secret for the registered application
const credential = new DefaultAzureCredential();
const account = "<account name>";
const tableName = "<tableName>";

const clientWithAAD = new TableClient(
  `https://${account}.table.core.windows.net`,
  tableName,
  credential
);

테이블의 엔터티 나열

함수를 호출하는 instance 통해 테이블 내의 엔터티를 TableClient 나열할 listEntities 수 있습니다. 이 함수는 를 사용하여 사용할 수 있는 을 PageableAsyncIterator 반환합니다. for-await-of

const { TableClient, AzureNamedKeyCredential } = require("@azure/data-tables");

const account = "<account>";
const accountKey = "<accountkey>";
const tableName = "<tableName>";

const credential = new AzureNamedKeyCredential(account, accountKey);
const client = new TableClient(`https://${account}.table.core.windows.net`, tableName, credential);

async function main() {
  let entitiesIter = client.listEntities();
  let i = 1;
  for await (const entity of entitiesIter) {
    console.log(`Entity${i}: PartitionKey: ${entity.partitionKey} RowKey: ${entity.rowKey}`);
    i++;
    // Output:
    // Entity1: PartitionKey: P1 RowKey: R1
    // Entity2: PartitionKey: P2 RowKey: R2
    // Entity3: PartitionKey: P3 RowKey: R3
    // Entity4: PartitionKey: P4 RowKey: R4
  }
}

main();

새 엔터티를 만들고 테이블에 추가합니다.

함수를 호출하는 instance 통해 테이블에 새 엔터티를 TableClientcreateEntity 만들 수 있습니다. 이 함수는 엔터티를 매개 변수로 삽입합니다. 엔터티에는 및 rowKey가 포함되어 partitionKey 야 합니다.

const { TableClient, AzureNamedKeyCredential } = require("@azure/data-tables");

const account = "<account>";
const accountKey = "<accountkey>";
const tableName = "<tableName>";

const credential = new AzureNamedKeyCredential(account, accountKey);
const client = new TableClient(`https://${account}.table.core.windows.net`, tableName, credential);

async function main() {
  const testEntity = {
    partitionKey: "P1",
    rowKey: "R1",
    foo: "foo",
    bar: 123
  };
  await client.createEntity(testEntity);
}

main();

Azurite 및 스토리지 에뮬레이터

Azure Tables 클라이언트 SDK는 Azure Storage 및 Tables API 호환 서버 에뮬레이터인 Azurite에서도 작동합니다. 사용을 시작하는 방법은 (Azurite 리포지토리)를 참조하세요.

연결 문자열 바로 가기를 사용하여 Azurite에 연결

애플리케이션에서 Azurite에 연결하는 가장 쉬운 방법은 바로 가기를 참조하는 연결 문자열을 구성하는 것입니다 UseDevelopmentStorage=true. 바로 가기는 각 Azure Storage 서비스에 대한 계정 이름, 계정 키 및 에뮬레이터 엔드포인트를 지정하는 에뮬레이터의 전체 연결 문자열과 같습니다(자세한 내용 참조). 이 바로 가기를 사용하여 Azure Tables 클라이언트 SDK는 기본 연결 문자열과 allowInsecureConnection 클라이언트 옵션을 설정합니다.

import { TableClient } from "@azure/data-tables";

const connectionString = "UseDevelopmentStorage=true";
const client = TableClient.fromConnectionString(connectionString, "myTable");

연결 문자열 바로 가기 없이 Azurite에 연결

서비스 URL 및 AzureNamedKeyCredential 사용자 지정 연결 문자열을 지정하여 연결 문자열 바로 가기를 사용하지 않고 azurite에 수동으로 연결할 수 있습니다. 그러나 allowInsecureConnection Azurite가 엔드포인트에서 http 실행되는 경우 를 수동으로 설정해야 합니다.

import { TableClient, AzureNamedKeyCredential } from "@azure/data-tables";

const client = new TableClient(
  "<Azurite-http-table-endpoint>",
  "myTable",
  new AzureNamedKeyCredential("<Azurite-account-name>", "<Azurite-account-key>"),
  { allowInsecureConnection: true }
);

문제 해결

일반

Javascript/Typescript SDK를 사용하여 Tables 서비스와 상호 작용하는 경우 서비스에서 반환된 오류는 REST API 요청에 대해 반환된 동일한 HTTP 상태 코드에 해당합니다. 스토리지 테이블 서비스 오류 코드

로깅

로깅을 사용하도록 설정하면 실패에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info로 설정합니다. 또는 @azure/logger에서 setLogLevel을 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

다음 단계

추가 코드 샘플 출시 예정 문제#10531

참여

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 https://cla.microsoft.com 을 참조하세요.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.

이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

Impressions