Share via


TableClient class

Um TableClient representa um Cliente para o serviço Tabelas do Azure, permitindo-lhe realizar operações numa ú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 um pedido HTTP para um URL. Os pipelines podem ter várias políticas para gerir a manipulação de cada pedido antes e depois de ser efetuada ao servidor.

tableName

Nome da tabela na qual realizar 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 transmitido para o construtor cliente

deleteEntity(string, string, DeleteTableEntityOptions)

Elimina a entidade especificada na tabela.

deleteTable(OperationOptions)

Elimina permanentemente a tabela atual com todas as respetivas entidades.

fromConnectionString(string, string, TableServiceClientOptions)

Cria uma instância de TableClient a partir da cadeia de ligação.

getAccessPolicy(OperationOptions)

Obtém detalhes sobre quaisquer políticas de acesso armazenadas especificadas na tabela que possam ser utilizadas com Assinaturas de Acesso Partilhado.

getEntity<T>(string, string, GetTableEntityOptions)

Devolve uma única entidade na tabela.

listEntities<T>(ListTableEntitiesOptions)

Consulta entidades numa tabela.

setAccessPolicy(SignedIdentifier[], OperationOptions)

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

submitTransaction(TransactionAction[])

Submete uma Transação composta por um conjunto de ações. Pode fornecer as ações como uma lista ou pode utilizar TableTransaction para ajudar a criar a transação.

Utilização de exemplo:

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

Utilização de exemplo 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

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

tableName

string

o nome da tabela

credential
NamedKeyCredential

NamedKeyCredential utilizado para autenticar pedidos. Apenas Suportado para o Nó

options
TableServiceClientOptions

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

Exemplo com 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

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

tableName

string

o nome da tabela

credential
SASCredential

SASCredential utilizado para autenticar pedidos

options
TableServiceClientOptions

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

Exemplo com um Token de 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 carateres do Cliente a apontar para o serviço de tabela do Armazenamento do Azure, como "https://myaccount.table.core.windows.net". 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 a acrescentar um token de 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

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

tableName

string

o nome da tabela

credential
TokenCredential

Credencial do Azure Active Directory utilizada para autenticar pedidos

options
TableServiceClientOptions

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

Exemplo com uma credencial do Azure Active 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 um pedido HTTP para um URL. Os pipelines podem ter várias políticas para gerir a manipulação de cada pedido antes e depois de ser efetuada ao servidor.

pipeline: Pipeline

Valor de Propriedade

tableName

Nome da tabela na qual realizar 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 de tabela.

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

Elimina 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 eliminaçã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)

Elimina permanentemente a tabela atual com todas as respetivas entidades.

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

Parâmetros

options
OperationOptions

Os parâmetros de opções.

Exemplo de eliminaçã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 ligação.

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

Parâmetros

connectionString

string

Cadeia de ligação de conta ou uma cadeia de ligação SAS de uma conta de armazenamento do Azure. [ Nota - a cadeia de ligação da conta só pode ser utilizada no NODE.JS runtime. ] Exemplo de cadeia de ligação de conta -DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net Exemplo de cadeia de ligaçã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 ligação especificada.

getAccessPolicy(OperationOptions)

Obtém detalhes sobre quaisquer políticas de acesso armazenadas especificadas na tabela que possam ser utilizadas com Assinaturas de Acesso Partilhado.

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

Parâmetros

options
OperationOptions

Os parâmetros de opções.

Devoluções

getEntity<T>(string, string, GetTableEntityOptions)

Devolve 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 numa 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 as políticas de acesso armazenadas para a tabela que podem ser utilizadas com Assinaturas de Acesso Partilhado.

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

Parâmetros

tableAcl

SignedIdentifier[]

A Lista de Controlo de Acesso para a tabela.

options
OperationOptions

Os parâmetros de opções.

Devoluções

submitTransaction(TransactionAction[])

Submete uma Transação composta por um conjunto de ações. Pode fornecer as ações como uma lista ou pode utilizar TableTransaction para ajudar a criar a transação.

Utilização de exemplo:

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

Utilização de exemplo 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[]

cadeia de identificação que contém a ação a executar e a entidade para executar a ação 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 atualizar.

mode
UpdateMode

Os diferentes modos para atualizar a entidade: - Intercalar: Atualizações uma entidade ao atualizar as propriedades da entidade sem substituir a entidade existente. - Substitua: Atualizações uma entidade existente ao substituir 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 de tabela.

mode
UpdateMode

Os diferentes modos para atualizar a entidade: - Intercalar: Atualizações uma entidade ao atualizar as propriedades da entidade sem substituir a entidade existente. - Substitua: Atualizações uma entidade existente ao substituir toda a entidade.

options
OperationOptions

Os parâmetros de opções.

Exemplo de aumento 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