All files / src table-client.ts

90.36% Statements 75/83
87.3% Branches 55/63
94.73% Functions 18/19
90.24% Lines 74/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326                                                                                                                                4x 4x 4x                   29x 29x 29x 29x 29x 29x 29x 29x 29x       2x                     7x 7x 1x     6x 1x     5x         2x       2x       2x                 3x               6x               1x     1x 1x                         6x 6x   6x   7x     7x 7x                 7x       7x 7x 14x 14x 2x       7x 7x 7x                 3x 3x 3x 3x 3x   3x 9x 9x                                       3x   3x       3x       3x   7x   7x 3x 1x           2x 1x         1x                 9x                     9x       9x       17x         11x       23x             9x 2x             7x 7x 7x 3x     4x              
import { AzureRequestError } from './azure-request-error'
import { paginate } from './internal/paging'
import type { ListOptions } from './internal/paging'
import { encodeUtf8 } from './internal/storage-encoding'
import {
  StorageTransport,
  multipartBoundary,
  storageRequestError,
  tableProtocol,
} from './internal/storage-request'
import type { StorageClientOptions, StorageCredential } from './internal/storage-request'
import {
  appendUrlPath,
  extendUrlPath,
  normalizeStorageUrl,
  rejectStorageUrlDotSegments,
} from './internal/storage-url'
import {
  parseEntity,
  parseEntityList,
  serializeEntity,
  serializeSelect,
} from './internal/table-entity'
import type { TableEntity, TableEntityResult } from './internal/table-entity'
import { createTable, deleteTable, escapeODataKey } from './internal/table-requests'
import type { TableCreateIfNotExistsResponse, TableDeleteResponse } from './internal/table-requests'
import { encodeResourceSegment } from './internal/url'
 
/** Merge keeps properties absent from the written entity; Replace removes them. */
export type TableUpdateMode = 'Merge' | 'Replace'
 
export interface TableEtagOptions {
  /** Sent as `If-Match`, so a stale etag fails with 412. Defaults to `*`. */
  etag?: string
}
 
export interface TableEntityWriteResponse {
  /** The new etag; undefined when a browser's CORS rules don't expose the ETag header. */
  etag?: string
}
 
export interface TableEntityQueryOptions {
  /** OData filter expression, for example built with `odata`. */
  filter?: string
  /** Properties to return; a projection may omit the keys and timestamp. */
  select?: string[]
}
 
export type TableTransactionAction =
  | { action: 'create'; entity: TableEntity }
  | { action: 'update' | 'upsert'; entity: TableEntity; mode?: TableUpdateMode }
  | { action: 'delete'; partitionKey: string; rowKey: string }
 
export interface TableTransactionResponse {
  status: number
  subResponses: { status: number }[]
}
 
export interface TableEntityResponse {
  readonly value: TableEntityResult[]
  continuationToken?: string
}
 
// The Table service returns at most 1,000 entities per query request.
const maxTablePageSize = 1000
const subResponseStatusPattern = /HTTP\/1\.[01] (\d{3})/gu
const updateMethods = { Merge: 'PATCH', Replace: 'PUT' } as const
 
export class TableClient {
  public readonly url: string
  public readonly tableName: string
  private readonly serviceUrl: string
  private readonly transport: StorageTransport
 
  /** `url` addresses the table, for example `https://account.table.core.windows.net/mytable`. */
  public constructor(url: string, credential?: StorageCredential, options?: StorageClientOptions) {
    rejectStorageUrlDotSegments(url)
    this.url = normalizeStorageUrl(url)
    const serviceUrl = new URL(this.url)
    const segments = serviceUrl.pathname.split('/')
    this.tableName = decodeURIComponent(segments.pop() ?? '')
    encodeResourceSegment(this.tableName, 'Table name')
    serviceUrl.pathname = segments.join('/')
    this.serviceUrl = serviceUrl.toString()
    this.transport = new StorageTransport(credential, options, tableProtocol)
  }
 
  public async createIfNotExists(): Promise<TableCreateIfNotExistsResponse> {
    return await createTable(this.transport, this.serviceUrl, this.tableName)
  }
 
  public async deleteIfExists(): Promise<TableDeleteResponse> {
    return await deleteTable(this.transport, this.serviceUrl, this.tableName)
  }
 
  public async getEntity(
    partitionKey: string,
    rowKey: string,
  ): Promise<TableEntityResult | undefined> {
    const response = await this.transport.send('GET', this.entityUrl(partitionKey, rowKey))
    if (response.status === 404) {
      return undefined
    }
 
    if (!response.ok) {
      throw storageRequestError('Get entity', response)
    }
 
    return parseEntity(await response.json())
  }
 
  /** Inserts the entity; an existing entity with the same keys fails with 409. */
  public async createEntity(entity: TableEntity): Promise<TableEntityWriteResponse> {
    const response = await this.transport.send('POST', this.url, {
      headers: { 'Content-Type': 'application/json', Prefer: 'return-no-content' },
      body: serializeEntity(entity),
    })
    Iif (!response.ok) {
      throw storageRequestError('Create entity', response)
    }
 
    return writeResponse(response)
  }
 
  /** Updates an existing entity; a missing entity fails with 404. */
  public async updateEntity(
    entity: TableEntity,
    mode: TableUpdateMode,
    options: TableEtagOptions = {},
  ): Promise<TableEntityWriteResponse> {
    return await this.writeEntity('Update entity', entity, mode, options.etag ?? '*')
  }
 
  /** Inserts the entity or updates an existing one with the same keys, replacing it by default. */
  public async upsertEntity(
    entity: TableEntity,
    mode: TableUpdateMode = 'Replace',
  ): Promise<TableEntityWriteResponse> {
    return await this.writeEntity('Upsert entity', entity, mode)
  }
 
  public async deleteEntity(
    partitionKey: string,
    rowKey: string,
    options: TableEtagOptions = {},
  ): Promise<TableDeleteResponse> {
    const response = await this.transport.send('DELETE', this.entityUrl(partitionKey, rowKey), {
      headers: { 'If-Match': options.etag ?? '*' },
    })
    Eif (response.status === 404) {
      return { succeeded: false, errorCode: 'ResourceNotFound' }
    }
 
    if (!response.ok) {
      throw storageRequestError('Delete entity', response)
    }
 
    return { succeeded: true }
  }
 
  public listEntities(query: TableEntityQueryOptions = {}): {
    byPage: (options?: ListOptions) => AsyncIterable<TableEntityResponse>
  } {
    const select = query.select === undefined ? undefined : serializeSelect(query.select)
    return {
      byPage: (options = {}) =>
        paginate(async (continuationToken) => {
          const top =
            options.maxPageSize === undefined
              ? undefined
              : String(Math.min(options.maxPageSize, maxTablePageSize))
          const cursor = new URLSearchParams(continuationToken)
          const response = await this.transport.send('GET', extendUrlPath(this.url, '()'), {
            query: {
              $filter: query.filter,
              $select: select,
              $top: top,
              NextPartitionKey: cursor.get('NextPartitionKey') ?? undefined,
              NextRowKey: cursor.get('NextRowKey') ?? undefined,
            },
          })
          Iif (!response.ok) {
            throw storageRequestError('List entities', response)
          }
 
          const next = new URLSearchParams()
          for (const name of ['NextPartitionKey', 'NextRowKey']) {
            const value = response.headers.get(`x-ms-continuation-${name}`)
            if (value !== null && value !== '') {
              next.set(name, value)
            }
          }
 
          const nextToken = next.size > 0 ? next.toString() : undefined
          const value = parseEntityList(await response.json())
          return { page: { value, continuationToken: nextToken }, continuationToken: nextToken }
        }, options.continuationToken),
    }
  }
 
  /** Runs all actions atomically; they must target one partition and distinct entities. */
  public async submitTransaction(
    actions: TableTransactionAction[],
  ): Promise<TableTransactionResponse> {
    const batch = multipartBoundary('batch')
    const changeset = multipartBoundary('changeset')
    const tableUrl = new URL(this.url)
    tableUrl.search = ''
    const lines = [`--${batch}`, `Content-Type: multipart/mixed; boundary=${changeset}`, '']
 
    for (const [index, action] of actions.entries()) {
      const { method, url, body, ifMatch } = transactionRequest(action, tableUrl.toString())
      lines.push(
        `--${changeset}`,
        'Content-Type: application/http',
        'Content-Transfer-Encoding: binary',
        `Content-ID: ${index + 1}`,
        '',
        `${method} ${url} HTTP/1.1`,
        'Accept: application/json;odata=nometadata',
        ...(body === undefined
          ? []
          : [
              'Content-Type: application/json',
              'Prefer: return-no-content',
              `Content-Length: ${encodeUtf8(body).byteLength}`,
            ]),
        ...(ifMatch ? ['If-Match: *'] : []),
        '',
        body ?? '',
      )
    }
    lines.push(`--${changeset}--`, `--${batch}--`, '')
 
    const response = await this.transport.send('POST', appendUrlPath(this.serviceUrl, '$batch'), {
      headers: { Accept: 'application/json', 'Content-Type': `multipart/mixed; boundary=${batch}` },
      body: lines.join('\r\n'),
    })
    Iif (!response.ok) {
      throw storageRequestError('Table transaction', response)
    }
 
    const subResponses = Array.from(
      (await response.text()).matchAll(subResponseStatusPattern),
      ([, status]) => ({ status: Number(status) }),
    )
    const failed = subResponses.find(({ status }) => status < 200 || status >= 300)
    if (failed !== undefined) {
      throw new AzureRequestError(
        `Table transaction failed: sub-response returned ${failed.status}`,
        failed.status,
      )
    }
 
    if (subResponses.length !== actions.length) {
      throw new Error(
        `Table transaction response contained ${subResponses.length} sub-responses; expected ${actions.length}`,
      )
    }
 
    return { status: response.status, subResponses }
  }
 
  private async writeEntity(
    operation: string,
    entity: TableEntity,
    mode: TableUpdateMode,
    ifMatch?: string,
  ): Promise<TableEntityWriteResponse> {
    const response = await this.transport.send(
      updateMethods[mode],
      this.entityUrl(entity.partitionKey, entity.rowKey),
      {
        headers: {
          'Content-Type': 'application/json',
          ...(ifMatch === undefined ? {} : { 'If-Match': ifMatch }),
        },
        body: serializeEntity(entity),
      },
    )
    Iif (!response.ok) {
      throw storageRequestError(operation, response)
    }
 
    return writeResponse(response)
  }
 
  private entityUrl(partitionKey: string, rowKey: string): string {
    return extendUrlPath(this.url, entityPath(partitionKey, rowKey))
  }
}
 
function writeResponse(response: Response): TableEntityWriteResponse {
  return { etag: response.headers.get('ETag') ?? undefined }
}
 
function entityPath(partitionKey: string, rowKey: string): string {
  return `(PartitionKey='${escapeODataKey(partitionKey)}',RowKey='${escapeODataKey(rowKey)}')`
}
 
function transactionRequest(
  action: TableTransactionAction,
  tableUrl: string,
): { method: string; url: string; body?: string; ifMatch: boolean } {
  if (action.action === 'delete') {
    return {
      method: 'DELETE',
      url: extendUrlPath(tableUrl, entityPath(action.partitionKey, action.rowKey)),
      ifMatch: true,
    }
  }
 
  const { entity } = action
  const body = serializeEntity(entity)
  if (action.action === 'create') {
    return { method: 'POST', url: tableUrl, body, ifMatch: false }
  }
 
  return {
    method: updateMethods[action.mode ?? 'Replace'],
    url: extendUrlPath(tableUrl, entityPath(entity.partitionKey, entity.rowKey)),
    body,
    ifMatch: action.action === 'update',
  }
}