Compartilhar via


TableClient class

Um TableClient representa um cliente para o serviço Tabelas do Azure, permitindo que você execute operações em uma única tabela.

Construtores

TableClient(string, string, NamedKeyCredential, TableServiceClientOptions)

Cria uma nova instância da classe TableClient.

TableClient(string, string, SASCredential, TableServiceClientOptions)

Cria uma nova instância da classe TableClient.

TableClient(string, string, TableServiceClientOptions)

Cria uma instância do TableClient.

TableClient(string, string, TokenCredential, TableServiceClientOptions)

Cria uma nova instância da classe TableClient.

Propriedades

pipeline

Representa um pipeline para fazer uma solicitação HTTP para uma URL. Os pipelines podem ter várias políticas para gerenciar a manipulação de cada solicitação antes e depois de ela ser feita no servidor.

tableName

Nome da tabela na qual executar operações.

url

URL da Conta de Tabela

Métodos

createEntity<T>(TableEntity<T>, OperationOptions)

Inserir entidade na tabela.

createTable(OperationOptions)

Cria uma tabela com o tableName passado para o construtor do cliente

deleteEntity(string, string, DeleteTableEntityOptions)

Exclui a entidade especificada na tabela.

deleteTable(OperationOptions)

Exclui permanentemente a tabela atual com todas as suas entidades.

fromConnectionString(string, string, TableServiceClientOptions)

Cria uma instância de TableClient da cadeia de conexão.

getAccessPolicy(OperationOptions)

Recupera detalhes sobre as políticas de acesso armazenadas especificadas na tabela que podem ser usadas com assinaturas de acesso compartilhado.

getEntity<T>(string, string, GetTableEntityOptions)

Retorna uma única entidade na tabela.

listEntities<T>(ListTableEntitiesOptions)

Consulta entidades em uma tabela.

setAccessPolicy(SignedIdentifier[], OperationOptions)

Define as políticas de acesso armazenadas para a tabela que podem ser usadas com Assinaturas de Acesso Compartilhado.

submitTransaction(TransactionAction[], OperationOptions)

Envia uma transação composta por um conjunto de ações. Você pode fornecer as ações como uma lista ou pode usar TableTransaction para ajudar a compilar a transação.

Uso de exemplo:

import { DefaultAzureCredential } from "@azure/identity";
import { TableClient, TransactionAction } from "@azure/data-tables";

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

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

const actions: TransactionAction[] = [
  ["create", { partitionKey: "p1", rowKey: "1", data: "test1" }],
  ["delete", { partitionKey: "p1", rowKey: "2" }],
  ["update", { partitionKey: "p1", rowKey: "3", data: "newTest" }, "Merge"],
];
const result = await client.submitTransaction(actions);

Uso de exemplo com TableTransaction:

import { DefaultAzureCredential } from "@azure/identity";
import { TableClient, TableTransaction } from "@azure/data-tables";

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

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

const transaction = new TableTransaction();

// Call the available action in the TableTransaction object
transaction.createEntity({ partitionKey: "p1", rowKey: "1", data: "test1" });
transaction.deleteEntity("p1", "2");
transaction.updateEntity({ partitionKey: "p1", rowKey: "3", data: "newTest" }, "Merge");

// submitTransaction with the actions list on the transaction.
const result = await client.submitTransaction(transaction.actions);
updateEntity<T>(TableEntity<T>, UpdateMode, UpdateTableEntityOptions)

Atualize uma entidade na tabela.

upsertEntity<T>(TableEntity<T>, UpdateMode, OperationOptions)

Insira uma entidade na tabela.

Detalhes do construtor

TableClient(string, string, NamedKeyCredential, TableServiceClientOptions)

Cria uma nova instância da classe TableClient.

new TableClient(url: string, tableName: string, credential: NamedKeyCredential, options?: TableServiceClientOptions)

Parâmetros

url

string

A URL da conta de serviço que é o destino da operação desejada, como "https://myaccount.table.core.windows.net".

tableName

string

o nome da tabela

credential
NamedKeyCredential

NamedKeyCredential usado para autenticar solicitações. Suporte somente para o Nó

options
TableServiceClientOptions

Opcional. Opções para configurar o pipeline HTTP.

Exemplo usando um nome/chave de conta:

import { AzureNamedKeyCredential, TableClient } from "@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(string, string, SASCredential, TableServiceClientOptions)

Cria uma nova instância da classe TableClient.

new TableClient(url: string, tableName: string, credential: SASCredential, options?: TableServiceClientOptions)

Parâmetros

url

string

A URL da conta de serviço que é o destino da operação desejada, como "https://myaccount.table.core.windows.net".

tableName

string

o nome da tabela

credential
SASCredential

SASCredential usado para autenticar solicitações

options
TableServiceClientOptions

Opcional. Opções para configurar o pipeline HTTP.

Exemplo usando um token SAS:

import { TableClient, AzureSASCredential } from "@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(string, string, TableServiceClientOptions)

Cria uma instância do TableClient.

new TableClient(url: string, tableName: string, options?: TableServiceClientOptions)

Parâmetros

url

string

Uma cadeia de caracteres do cliente apontando para o serviço de tabela do Armazenamento do Azure, como "https://myaccount.table.core.windows.net". Você pode acrescentar uma SAS, como "https://myaccount.table.core.windows.net?sasString".

tableName

string

o nome da tabela

options
TableServiceClientOptions

Opções para configurar o pipeline HTTP.

Exemplo de anexação de um token SAS:

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

const account = "<account name>";
const sasToken = "<SAS token>";
const tableName = "<tableName>";

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

TableClient(string, string, TokenCredential, TableServiceClientOptions)

Cria uma nova instância da classe TableClient.

new TableClient(url: string, tableName: string, credential: TokenCredential, options?: TableServiceClientOptions)

Parâmetros

url

string

A URL da conta de serviço que é o destino da operação desejada, como "https://myaccount.table.core.windows.net".

tableName

string

o nome da tabela

credential
TokenCredential

Credencial do Azure Active Directory usada para autenticar solicitações

options
TableServiceClientOptions

Opcional. Opções para configurar o pipeline HTTP.

Exemplo usando uma credencial do Azure Active Directory:

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

const credential = new DefaultAzureCredential();
const account = "<account name>";
const tableName = "<tableName>";

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

Detalhes da propriedade

pipeline

Representa um pipeline para fazer uma solicitação HTTP para uma URL. Os pipelines podem ter várias políticas para gerenciar a manipulação de cada solicitação antes e depois de ela ser feita no servidor.

pipeline: Pipeline

Valor da propriedade

tableName

Nome da tabela na qual executar operações.

tableName: string

Valor da propriedade

string

url

URL da Conta de Tabela

url: string

Valor da propriedade

string

Detalhes do método

createEntity<T>(TableEntity<T>, OperationOptions)

Inserir entidade na tabela.

function createEntity<T>(entity: TableEntity<T>, options?: OperationOptions): Promise<TableInsertEntityHeaders>

Parâmetros

entity

TableEntity<T>

As propriedades da entidade de tabela.

options
OperationOptions

Os parâmetros de opções.

Exemplo de criação de uma entidade

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

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

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

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

Retornos

createTable(OperationOptions)

Cria uma tabela com o tableName passado para o construtor do cliente

function createTable(options?: OperationOptions): Promise<void>

Parâmetros

options
OperationOptions

Os parâmetros de opções.

Exemplo de criação de uma tabela

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

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

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

// If the table 'newTable' already exists, createTable doesn't throw
await client.createTable();

Retornos

Promise<void>

deleteEntity(string, string, DeleteTableEntityOptions)

Exclui a entidade especificada na tabela.

function deleteEntity(partitionKey: string, rowKey: string, options?: DeleteTableEntityOptions): Promise<TableDeleteEntityHeaders>

Parâmetros

partitionKey

string

A chave de partição da entidade.

rowKey

string

A chave de linha da entidade.

options
DeleteTableEntityOptions

Os parâmetros de opções.

Exemplo de exclusão de uma entidade

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

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

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

// deleteEntity deletes the entity that matches exactly the partitionKey and rowKey
await client.deleteEntity("<partitionKey>", "<rowKey>");

Retornos

deleteTable(OperationOptions)

Exclui permanentemente a tabela atual com todas as suas entidades.

function deleteTable(options?: OperationOptions): Promise<void>

Parâmetros

options
OperationOptions

Os parâmetros de opções.

Exemplo excluindo uma tabela

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

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

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

await client.deleteTable();

Retornos

Promise<void>

fromConnectionString(string, string, TableServiceClientOptions)

Cria uma instância de TableClient da cadeia de conexão.

static function fromConnectionString(connectionString: string, tableName: string, options?: TableServiceClientOptions): TableClient

Parâmetros

connectionString

string

Cadeia de conexão de conta ou uma cadeia de conexão SAS de uma conta de armazenamento do Azure. [ Observação - A cadeia de conexão da conta só pode ser usada em NODE.JS runtime. ] Exemplo de cadeia de conexão da conta – DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net exemplo de cadeia de conexão SAS – BlobEndpoint=https://myaccount.table.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString

tableName

string

options
TableServiceClientOptions

Opções para configurar o pipeline HTTP.

Retornos

Um novo TableClient da cadeia de conexão fornecida.

getAccessPolicy(OperationOptions)

Recupera detalhes sobre as políticas de acesso armazenadas especificadas na tabela que podem ser usadas com assinaturas de acesso compartilhado.

function getAccessPolicy(options?: OperationOptions): Promise<GetAccessPolicyResponse>

Parâmetros

options
OperationOptions

Os parâmetros de opções.

Retornos

getEntity<T>(string, string, GetTableEntityOptions)

Retorna uma única entidade na tabela.

function getEntity<T>(partitionKey: string, rowKey: string, options?: GetTableEntityOptions): Promise<GetTableEntityResponse<TableEntityResult<T>>>

Parâmetros

partitionKey

string

A chave de partição da entidade.

rowKey

string

A chave de linha da entidade.

options
GetTableEntityOptions

Os parâmetros de opções.

Exemplo de obtenção de uma entidade

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

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

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

const entity = await client.getEntity("<partitionKey>", "<rowKey>");
console.log(`Entity: PartitionKey: ${entity.partitionKey} RowKey: ${entity.rowKey}`);

Retornos

listEntities<T>(ListTableEntitiesOptions)

Consulta entidades em uma tabela.

function listEntities<T>(options?: ListTableEntitiesOptions): PagedAsyncIterableIterator<TableEntityResult<T>, TableEntityResultPage<T>, PageSettings>

Parâmetros

options
ListTableEntitiesOptions

Os parâmetros de opções.

Exemplo de entidades de listagem

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

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

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

let i = 0;
const entities = client.listEntities();
for await (const entity of entities) {
  console.log(`Entity${++i}: PartitionKey: ${entity.partitionKey} RowKey: ${entity.rowKey}`);
}

Retornos

setAccessPolicy(SignedIdentifier[], OperationOptions)

Define as políticas de acesso armazenadas para a tabela que podem ser usadas com Assinaturas de Acesso Compartilhado.

function setAccessPolicy(tableAcl: SignedIdentifier[], options?: OperationOptions): Promise<TableSetAccessPolicyHeaders>

Parâmetros

tableAcl

SignedIdentifier[]

A Lista de Controle de Acesso para a tabela.

options
OperationOptions

Os parâmetros de opções.

Retornos

submitTransaction(TransactionAction[], OperationOptions)

Envia uma transação composta por um conjunto de ações. Você pode fornecer as ações como uma lista ou pode usar TableTransaction para ajudar a compilar a transação.

Uso de exemplo:

import { DefaultAzureCredential } from "@azure/identity";
import { TableClient, TransactionAction } from "@azure/data-tables";

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

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

const actions: TransactionAction[] = [
  ["create", { partitionKey: "p1", rowKey: "1", data: "test1" }],
  ["delete", { partitionKey: "p1", rowKey: "2" }],
  ["update", { partitionKey: "p1", rowKey: "3", data: "newTest" }, "Merge"],
];
const result = await client.submitTransaction(actions);

Uso de exemplo com TableTransaction:

import { DefaultAzureCredential } from "@azure/identity";
import { TableClient, TableTransaction } from "@azure/data-tables";

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

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

const transaction = new TableTransaction();

// Call the available action in the TableTransaction object
transaction.createEntity({ partitionKey: "p1", rowKey: "1", data: "test1" });
transaction.deleteEntity("p1", "2");
transaction.updateEntity({ partitionKey: "p1", rowKey: "3", data: "newTest" }, "Merge");

// submitTransaction with the actions list on the transaction.
const result = await client.submitTransaction(transaction.actions);
function submitTransaction(actions: TransactionAction[], options?: OperationOptions): Promise<TableTransactionResponse>

Parâmetros

actions

TransactionAction[]

tupla que contém a ação a ser executada e a entidade para executar a ação com

options
OperationOptions

Opções para a solicitação.

Retornos

updateEntity<T>(TableEntity<T>, UpdateMode, UpdateTableEntityOptions)

Atualize uma entidade na tabela.

function updateEntity<T>(entity: TableEntity<T>, mode?: UpdateMode, options?: UpdateTableEntityOptions): Promise<TableUpdateEntityHeaders>

Parâmetros

entity

TableEntity<T>

As propriedades da entidade a ser atualizada.

mode
UpdateMode

Os diferentes modos para atualizar a entidade: – Mesclagem: atualiza uma entidade atualizando as propriedades da entidade sem substituir a entidade existente. - Substituir: atualiza uma entidade existente substituindo toda a entidade.

options
UpdateTableEntityOptions

Os parâmetros de opções.

Exemplo de atualização de uma entidade

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

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

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

const entity = { partitionKey: "p1", rowKey: "r1", bar: "updatedBar" };

// Update uses update mode "Merge" as default
// merge means that update will match a stored entity
// that has the same partitionKey and rowKey as the entity
// passed to the method and then will only update the properties present in it.
// Any other properties that are not defined in the entity passed to updateEntity
// will remain as they are in the service
await client.updateEntity(entity);

// We can also set the update mode to Replace, which will match the entity passed
// to updateEntity with one stored in the service and replace with the new one.
// If there are any missing properties in the entity passed to updateEntity, they
// will be removed from the entity stored in the service
await client.updateEntity(entity, "Replace");

Retornos

upsertEntity<T>(TableEntity<T>, UpdateMode, OperationOptions)

Insira uma entidade na tabela.

function upsertEntity<T>(entity: TableEntity<T>, mode?: UpdateMode, options?: OperationOptions): Promise<TableMergeEntityHeaders>

Parâmetros

entity

TableEntity<T>

As propriedades da entidade de tabela.

mode
UpdateMode

Os diferentes modos para atualizar a entidade: – Mesclagem: atualiza uma entidade atualizando as propriedades da entidade sem substituir a entidade existente. - Substituir: atualiza uma entidade existente substituindo toda a entidade.

options
OperationOptions

Os parâmetros de opções.

Exemplo de upserting de uma entidade

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

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

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

const entity = { partitionKey: "p1", rowKey: "r1", bar: "updatedBar" };

// Upsert uses update mode "Merge" as default.
// This behaves similarly to update but creates the entity
// if it doesn't exist in the service
await client.upsertEntity(entity);

// We can also set the update mode to Replace.
// This behaves similarly to update but creates the entity
// if it doesn't exist in the service
await client.upsertEntity(entity, "Replace");

Retornos