updating az tables

This commit is contained in:
2024-11-19 20:51:31 -06:00
parent 67014a3080
commit 41a1b9f807
3 changed files with 38 additions and 6 deletions

View File

@@ -1,3 +1,6 @@
export interface TableOptions {
connectionString;
accountName: string;
accountKey: string;
accountUrl: string;
allowInsecureConnection: boolean;
}

View File

@@ -1,7 +1,7 @@
import { Inject, Injectable } from '@nestjs/common';
import { TableOptions } from './az-table.interface';
import { TABLE_OPTIONS } from './az-table.constants';
import { TableClient } from '@azure/data-tables';
import { TableClient, AzureNamedKeyCredential, TableServiceClient, TableServiceClientOptions } from '@azure/data-tables';
@Injectable()
export class TableService {
@@ -10,9 +10,38 @@ export class TableService {
private tablesOptions: TableOptions
) {}
async getTableClient(tableName: string): Promise<TableClient> {
const tableClient: TableClient = new TableClient(this.tablesOptions.connectionString, tableName);
async checkTableExists(tableName: string, tableServiceClient: TableServiceClient): Promise<boolean> {
const tables = tableServiceClient.listTables();
let tableExists: boolean = false;
return tableClient;
for await (const table of tables) {
if (table.name === tableName) {
tableExists = true;
break;
}
}
return tableExists;
}
async getTableClient(tableName: string): Promise<TableClient> {
try {
const credential: AzureNamedKeyCredential = new AzureNamedKeyCredential(this.tablesOptions.accountName, this.tablesOptions.accountKey);
const options: TableServiceClientOptions = { allowInsecureConnection: this.tablesOptions.allowInsecureConnection };
const tableServiceClient: TableServiceClient = new TableServiceClient(this.tablesOptions.accountUrl, credential, options);
const tableExists: boolean = await this.checkTableExists(tableName, tableServiceClient);
if (!tableExists) {
await tableServiceClient.createTable(tableName);
}
const tableClient: TableClient = new TableClient(this.tablesOptions.accountUrl, tableName, credential, options);
return tableClient;
} catch (error) {
console.log(error);
return error;
}
}
}