All files / utils commentCount.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 107 10833x 33x     33x                                 55x                                               10x 10x 10x     2x                       15x                                   43x 184x 43x   30x 31x 31x     184x       31x   7x     30x     33x            
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 comment count by
 * `delta`. Same mechanics as itemLikeCount.js's buildLikeCountUpdate: the row
 * auto-vivifies on the first ADD, and a decrement carries a floor condition
 * (see isCountFloorCancellation in counterFloor.js).
 *
 * The count is the number of *approved* comments at every level (top-level
 * comments and replies). Pending, rejected and deleted comments are not
 * counted — see docs/architecture/MODERATION.md.
 *
 * @param {string} tableName
 * @param {string} itemId
 * @param {number} delta
 */
function buildCommentCountUpdate(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 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 adjustCommentCount(docClient, tableName, itemId, delta) {
  const { Update: update } = buildCommentCountUpdate(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 comment-count row entirely (item or entity deletion).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} itemId
 */
async function deleteCommentCount(docClient, tableName, itemId) {
  await docClient.send(
    new DeleteCommand({
      TableName: tableName,
      Key: { itemId }
    })
  )
}
 
/**
 * Batch-reads comment counts for many items at once. Items with no row yet
 * (never commented) default to 0.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string[]} itemIds
 * @returns {Promise<Map<string, number>>}
 */
async function getCommentCounts(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 = {
  buildCommentCountUpdate,
  adjustCommentCount,
  deleteCommentCount,
  getCommentCounts
}