Partilhar via


TableClient class

Um TableClient representa um Client para o serviço de 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 de 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 ao 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 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 a partir da cadeia de conexão.

getAccessPolicy(OperationOptions)

Recupera detalhes sobre quaisquer políticas de acesso armazenado 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 políticas de acesso armazenado para a tabela que podem ser usadas com Assinaturas de Acesso Compartilhado.

submitTransaction(TransactionAction[], OperationOptions)

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

Exemplo de uso:

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);

Exemplo de uso 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)

Atualizar uma entidade na tabela.

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

Upsert 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. Apenas suportado para 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 de TableClient.

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

Parâmetros

url

string

Uma cadeia de caracteres Client 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 acréscimo 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 Ative Directory usada para autenticar solicitações

options
TableServiceClientOptions

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

Exemplo usando uma credencial do Azure Ative 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 de 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 ao servidor.

pipeline: Pipeline

Valor de Propriedade

tableName

Nome da tabela na qual executar operações.

tableName: string

Valor de Propriedade

string

url

URL da Conta de Tabela

url: string

Valor de Propriedade

string

Detalhes de 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 table.

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);

Devoluções

createTable(OperationOptions)

Cria uma tabela com o tableName passado para o construtor 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();

Devoluções

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>");

Devoluções

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 de exclusã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);

await client.deleteTable();

Devoluções

Promise<void>

fromConnectionString(string, string, TableServiceClientOptions)

Cria uma instância de TableClient a partir 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 tempo de execução. ] Exemplo de cadeia de conexão de 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.

Devoluções

Um novo TableClient da cadeia de conexão fornecida.

getAccessPolicy(OperationOptions)

Recupera detalhes sobre quaisquer políticas de acesso armazenado 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.

Devoluções

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}`);

Devoluções

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 listagem de entidades

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}`);
}

Devoluções

setAccessPolicy(SignedIdentifier[], OperationOptions)

Define políticas de acesso armazenado 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.

Devoluções

submitTransaction(TransactionAction[], OperationOptions)

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

Exemplo de uso:

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);

Exemplo de uso 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 a ser executada com

options
OperationOptions

Opções para o pedido.

Devoluções

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

Atualizar 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 de atualização da entidade: - Mesclar: 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");

Devoluções

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

Upsert 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 table.

mode
UpdateMode

Os diferentes modos de atualização da entidade: - Mesclar: 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 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" };

// 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");

Devoluções