All files / utils batchWrite.js

100% Statements 19/19
100% Branches 8/8
100% Functions 4/4
100% Lines 16/16

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 5696x   96x 96x                           724x 250x 251x 251x 251x 255x             250x 223x 5x 5x                             610x     178x       96x  
const { BatchWriteCommand } = require('@aws-sdk/lib-dynamodb')
 
const BATCH_SIZE = 25
const MAX_RETRY_ATTEMPTS = 4
 
/**
 * Sends a list of BatchWriteItem requests to one table, chunked into
 * BatchWriteCommand calls of 25 with exponential-backoff retry on
 * UnprocessedItems. Requests are the raw shape BatchWriteItem expects —
 * `{ PutRequest: { Item } }` or `{ DeleteRequest: { Key } }` — and may be
 * freely mixed within one call (BatchWriteItem supports both kinds together).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {Array<{ PutRequest?: { Item: Record<string, unknown> }, DeleteRequest?: { Key: Record<string, unknown> } }>} requests
 */
async function batchWrite(docClient, tableName, requests) {
  if (requests.length === 0) return
  for (let i = 0; i < requests.length; i += BATCH_SIZE) {
    let unprocessed = requests.slice(i, i + BATCH_SIZE)
    let attempts = 0
    while (unprocessed.length > 0 && attempts < MAX_RETRY_ATTEMPTS) {
      const result = await docClient.send(
        new BatchWriteCommand({
          RequestItems: {
            [tableName]: unprocessed
          }
        })
      )
      unprocessed = result.UnprocessedItems?.[tableName] ?? []
      if (unprocessed.length > 0) {
        await new Promise((r) => setTimeout(r, 200 * 2 ** attempts))
        attempts++
      }
    }
  }
}
 
/**
 * Deletes many items from a table by key — a thin wrapper over batchWrite
 * for the (still very common) delete-only case.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {Array<Record<string, unknown>>} keys
 */
async function batchDelete(docClient, tableName, keys) {
  await batchWrite(
    docClient,
    tableName,
    keys.map((key) => ({ DeleteRequest: { Key: key } }))
  )
}
 
module.exports = { batchWrite, batchDelete }