All files / src/internal table-requests.ts

94.44% Statements 34/36
88.57% Branches 31/35
100% Functions 5/5
94.44% Lines 34/36

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        4x                           49x                 6x 6x 6x 15x 15x 4x   15x 10x 10x     5x       10x 1x 1x     9x 5x 5x   4x 2x     2x 1x     1x               2x         2x 1x     1x 1x                     3x 3x 3x 1x     2x       2x    
import { storageRequestError } from './storage-request'
import type { StorageTransport } from './storage-request'
import { appendUrlPath } from './storage-url'
 
const int64Suffix = /^[Ll]\b/u
 
export interface TableCreateIfNotExistsResponse {
  succeeded: boolean
  errorCode?: string
}
 
export interface TableDeleteResponse {
  succeeded: boolean
  errorCode?: string
}
 
/** Escapes a key for an OData path literal such as `Tables('name')`. */
export function escapeODataKey(key: string): string {
  return encodeURIComponent(key.replaceAll("'", "''"))
}
 
/**
 * Builds an OData filter such as odata`RowKey eq ${rowKey}`. Strings become quoted literals with
 * doubled apostrophes and Dates become `datetime'…'` literals. A string interpolated inside
 * a quoted template literal is escaped without adding a second pair of quotes.
 */
export function odata(strings: TemplateStringsArray, ...values: unknown[]): string {
  let filter = ''
  let quoted = false
  for (const [index, text] of strings.entries()) {
    filter += text
    if (text.split("'").length % 2 === 0) {
      quoted = !quoted
    }
    if (index < values.length) {
      const explicitInt64Suffix = int64Suffix.test(strings[index + 1] ?? '')
      filter += odataLiteral(values[index], quoted, explicitInt64Suffix)
    }
  }
  return filter
}
 
function odataLiteral(value: unknown, quoted: boolean, explicitInt64Suffix: boolean): string {
  if (value instanceof Date) {
    const iso = Date.prototype.toISOString.call(value)
    return quoted ? iso : `datetime'${iso}'`
  }
 
  if (typeof value === 'string') {
    const escaped = value.replaceAll("'", "''")
    return quoted ? escaped : `'${escaped}'`
  }
  if (typeof value === 'bigint') {
    return quoted || explicitInt64Suffix ? String(value) : `${String(value)}L`
  }
 
  if (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) {
    return String(value)
  }
 
  throw new TypeError('Unsupported OData literal value')
}
 
export async function createTable(
  transport: StorageTransport,
  serviceUrl: string,
  tableName: string,
): Promise<TableCreateIfNotExistsResponse> {
  const response = await transport.send('POST', appendUrlPath(serviceUrl, 'Tables'), {
    headers: { 'Content-Type': 'application/json', Prefer: 'return-no-content' },
    body: JSON.stringify({ TableName: tableName }),
  })
  // Other conflicts, such as TableBeingDeleted, are failures.
  if (response.status === 409 && response.headers.get('x-ms-error-code') === 'TableAlreadyExists') {
    return { succeeded: false, errorCode: 'TableAlreadyExists' }
  }
 
  Eif (!response.ok) {
    throw storageRequestError('Create table', response)
  }
 
  return { succeeded: true }
}
 
export async function deleteTable(
  transport: StorageTransport,
  serviceUrl: string,
  tableName: string,
): Promise<TableDeleteResponse> {
  const tableUrl = appendUrlPath(serviceUrl, `Tables('${escapeODataKey(tableName)}')`)
  const response = await transport.send('DELETE', tableUrl)
  if (response.status === 404) {
    return { succeeded: false, errorCode: 'TableNotFound' }
  }
 
  Iif (!response.ok) {
    throw storageRequestError('Delete table', response)
  }
 
  return { succeeded: true }
}