All files / utils itemLikeCount.js

100% Statements 24/24
87.5% Branches 7/8
100% Functions 6/6
100% Lines 20/20

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 10714x 14x     14x                           17x                                                 6x 6x 6x     2x                       6x                                     5x 154x 5x   4x 5x 5x     154x       5x   3x     4x     14x            
const { UpdateCommand, DeleteCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { withCountFloor } = require('./counterFloor')
 
// DynamoDB BatchGetItem accepts at most 100 keys per table per request.
const BATCH_GET_LIMIT = 100
 
/**
 * A TransactWriteItems `Update` action adjusting an item's like count by
 * `delta`. Auto-vivifies the row on first ADD, so nothing needs pre-seeding.
 * A decrement carries a floor condition so the count never goes below 0; when
 * it fails the transaction is cancelled and the caller must retry without the
 * count update (see isCountFloorCancellation in counterFloor.js).
 *
 * @param {string} tableName
 * @param {string} itemId
 * @param {number} delta
 */
function buildLikeCountUpdate(tableName, itemId, delta) {
  return {
    Update: withCountFloor(
      {
        TableName: tableName,
        Key: { itemId },
        UpdateExpression: 'ADD #count :delta',
        ExpressionAttributeNames: { '#count': 'count' },
        ExpressionAttributeValues: { ':delta': delta }
      },
      delta
    )
  }
}
 
/**
 * Non-transactional +/- adjustment, for best-effort call sites (deleting a
 * single user's likes across many items that aren't themselves being
 * deleted) that don't already run inside a TransactWriteCommand.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} itemId
 * @param {number} delta
 */
async function adjustLikeCount(docClient, tableName, itemId, delta) {
  const { Update: update } = buildLikeCountUpdate(tableName, itemId, delta)
  try {
    await docClient.send(new UpdateCommand(update))
  } catch (error) {
    // Decrement below 0 is refused: the count is already at its floor.
    if (error.name !== 'ConditionalCheckFailedException') throw error
  }
}
 
/**
 * Deletes an item's like-count row entirely (item or entity deletion).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} itemId
 */
async function deleteLikeCount(docClient, tableName, itemId) {
  await docClient.send(
    new DeleteCommand({
      TableName: tableName,
      Key: { itemId }
    })
  )
}
 
/**
 * Batch-reads like counts for many items at once (items/list.js enriches a
 * whole page of items per request). Items with no row yet (never liked)
 * default to 0.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string[]} itemIds
 * @returns {Promise<Map<string, number>>}
 */
async function getLikeCounts(docClient, tableName, itemIds) {
  const uniqueIds = Array.from(new Set(itemIds)).filter(Boolean)
  const counts = new Map(uniqueIds.map((itemId) => [itemId, 0]))
  if (uniqueIds.length === 0) return counts
 
  for (let offset = 0; offset < uniqueIds.length; offset += BATCH_GET_LIMIT) {
    const chunk = uniqueIds.slice(offset, offset + BATCH_GET_LIMIT)
    const result = await docClient.send(
      new BatchGetCommand({
        RequestItems: {
          [tableName]: { Keys: chunk.map((itemId) => ({ itemId })) }
        }
      })
    )
    for (const item of result.Responses?.[tableName] || []) {
      // Floor at 0: never display a negative count from historical desyncs.
      counts.set(item.itemId, Math.max(0, item.count || 0))
    }
  }
  return counts
}
 
module.exports = {
  buildLikeCountUpdate,
  adjustLikeCount,
  deleteLikeCount,
  getLikeCounts
}