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[])

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:

const { TableClient } = require("@azure/data-tables");
const connectionString = "<connection-string>"
const tableName = "<tableName>"
const client = TableClient.fromConnectionString(connectionString, tableName);
const actions = [
   ["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:

const { TableClient } = require("@azure/data-tables");
const connectionString = "<connection-string>"
const tableName = "<tableName>"
const client = TableClient.fromConnectionString(connectionString, tableName);
const transaction = new TableTransaction();
// Call the available action in the TableTransaction object
transaction.create({partitionKey: "p1", rowKey: "1", data: "test1"});
transaction.delete("p1", "2");
transaction.update({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:

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables");
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

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:

const { AzureSASCredential, TableClient } = require("@azure/data-tables");
const account = "<storage account name>";
const sasToken = "<sas-token>";
const tableName = "<table name>";
const sasCredential = new AzureSASCredential(sasToken);

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

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:

const { TableClient } = require("@azure/data-tables");
const account = "<storage account name>";
const sasToken = "<SAS token>";
const tableName = "<table name>";

const client = 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:

cons { DefaultAzureCredential } = require("@azure/identity");
const { AzureSASCredential, TableClient } = require("@azure/data-tables");
const account = "<storage account name>";
const sasToken = "<sas-token>";
const tableName = "<table name>";
const credential = new DefaultAzureCredential();

const client = 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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

// partitionKey and rowKey are required properties of the entity to create
// and accepts any other properties
await client.createEntity({partitionKey: "p1", rowKey: "r1", foo: "Hello!"});

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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

// calling create table will create the table used
// to instantiate the TableClient.
// Note: If the table already
// exists this function 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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

// deleteEntity deletes the entity that matches
// exactly the partitionKey and rowKey passed as parameters
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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

// calling deleteTable will delete the table used
// to instantiate the TableClient.
// Note: If the table doesn't exist this function doesn't fail.
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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

// getEntity will get a single entity stored in the service that
// matches exactly the partitionKey and rowKey used as parameters
// to the method.
const entity = await client.getEntity("<partitionKey>", "<rowKey>");
console.log(entity);

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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

// list entities returns a AsyncIterableIterator
// this helps consuming paginated responses by
// automatically handling getting the next pages
const entities = client.listEntities();

// this loop will get all the entities from all the pages
// returned by the service
for await (const entity of entities) {
   console.log(entity);
}

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[])

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:

const { TableClient } = require("@azure/data-tables");
const connectionString = "<connection-string>"
const tableName = "<tableName>"
const client = TableClient.fromConnectionString(connectionString, tableName);
const actions = [
   ["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:

const { TableClient } = require("@azure/data-tables");
const connectionString = "<connection-string>"
const tableName = "<tableName>"
const client = TableClient.fromConnectionString(connectionString, tableName);
const transaction = new TableTransaction();
// Call the available action in the TableTransaction object
transaction.create({partitionKey: "p1", rowKey: "1", data: "test1"});
transaction.delete("p1", "2");
transaction.update({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[]): Promise<TableTransactionResponse>

Parâmetros

actions

TransactionAction[]

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

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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

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

const { AzureNamedKeyCredential, TableClient } = require("@azure/data-tables")
const account = "<storage account name>";
const accountKey = "<account key>"
const tableName = "<table name>";
const sharedKeyCredential = new AzureNamedKeyCredential(account, accountKey);

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

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