All files / utils counterFloor.js

100% Statements 12/12
100% Branches 12/12
100% Functions 3/3
100% Lines 9/9

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                                122x 71x                               15x 12x 12x 7x 7x   6x       52x  
/**
 * Shared "never below 0" logic for the ADD-based counter tables
 * (subscribers, followers, likes).
 */
 
/**
 * Adds a floor condition to a decrementing counter `Update`, so the stored
 * count cannot go below 0. Increments are returned unchanged. When the
 * condition fails (count already 0 or missing) the write is refused.
 *
 * @template {object} T
 * @param {T & { ExpressionAttributeValues: Record<string, number> }} update
 * @param {number} delta
 * @returns {T}
 */
function withCountFloor(update, delta) {
  if (delta >= 0) return update
  return {
    ...update,
    ConditionExpression: '#count >= :min',
    ExpressionAttributeValues: { ...update.ExpressionAttributeValues, ':min': -delta }
  }
}
 
/**
 * True when a TransactionCanceledException was caused solely by the counter
 * floor condition (last item of the transaction) while all other items were
 * fine. The caller should then retry without the counter update.
 *
 * @param {Error & { CancellationReasons?: Array<{ Code?: string }> }} error
 * @returns {boolean}
 */
function isCountFloorCancellation(error) {
  if (error?.name !== 'TransactionCanceledException') return false
  const reasons = error.CancellationReasons || []
  if (reasons.length < 2) return false
  const last = reasons[reasons.length - 1]
  return (
    last?.Code === 'ConditionalCheckFailed' &&
    reasons.slice(0, -1).every((r) => !r?.Code || r.Code === 'None')
  )
}
 
module.exports = { withCountFloor, isCountFloorCancellation }