All files / entities createEntityRecord.js

100% Statements 13/13
100% Branches 7/7
100% Functions 1/1
100% Lines 13/13

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              3x                       106x           106x 103x 100x             3x 3x       2x       1x 1x 1x   1x       3x  
/**
 * Shared write path for creating one entity record, used by
 * entities/create.js, entities/fork.js and entities/import-worker.js — see
 * items/createItem.js for the item-side equivalent and the duplication this
 * class of extraction is meant to close.
 */
 
const { PutCommand, TransactWriteCommand } = require('@aws-sdk/lib-dynamodb')
 
/**
 * Writes one entity record, conditioned on its id not already existing —
 * together with `extraTransactItems` in one transaction when there are any.
 * `ConditionalCheckFailedException` propagates to the caller untouched —
 * each caller keeps its own handling (entities/create.js maps it to a 409;
 * entities/fork.js and entities/import-worker.js let it surface as an
 * unexpected error, since their ids are freshly generated and a collision is
 * not expected).
 */
async function putEntityRecord(docClient, tableName, entity, extraTransactItems = []) {
  const put = {
    TableName: tableName,
    Item: entity,
    ConditionExpression: 'attribute_not_exists(id)'
  }
 
  if (extraTransactItems.length === 0) {
    await docClient.send(new PutCommand(put))
    return
  }
 
  // Writes that must land with the entity or not at all (e.g. a restricted
  // entity's roles, UC-RBAC-008.1 AC-3). The entity's own id collision is
  // re-surfaced as the same ConditionalCheckFailedException the plain Put
  // throws, so callers' handling doesn't depend on which path ran.
  try {
    await docClient.send(
      new TransactWriteCommand({ TransactItems: [{ Put: put }, ...extraTransactItems] })
    )
  } catch (error) {
    if (
      error.name === 'TransactionCanceledException' &&
      error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed'
    ) {
      const conflict = new Error('An entity with this id already exists')
      conflict.name = 'ConditionalCheckFailedException'
      throw conflict
    }
    throw error
  }
}
 
module.exports = { putEntityRecord }