All files / utils itemLikes.js

100% Statements 27/27
75% Branches 9/12
100% Functions 7/7
100% Lines 25/25

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 10411x 11x 11x                         7x             7x     7x                                   33x               33x 33x     4x     33x 32x 3x           11x                               4x 4x 4x   2x 2x 2x     4x       2x 1x     2x     11x  
const { QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
const { adjustLikeCount } = require('./itemLikeCount')
 
/**
 * Deletes every like row for an item that is truly gone (item delete, or the
 * item's entity being deleted). ItemLikesTable is keyed itemId-first, so this
 * is a direct Query on the partition key — no GSI needed, unlike
 * deleteAllSubscriptionsForEntity in entitySubscriptions.js.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} itemId
 */
async function deleteAllLikesForItem(docClient, tableName, itemId) {
  const result = await docClient.send(
    new QueryCommand({
      TableName: tableName,
      KeyConditionExpression: 'itemId = :itemId',
      ExpressionAttributeValues: { ':itemId': itemId }
    })
  )
  await batchDelete(
    docClient,
    tableName,
    (result.Items || []).map((like) => ({ itemId: like.itemId, userId: like.userId }))
  )
}
 
/**
 * Deletes every like a given user has made on any item, regardless of who
 * owns those items. Used when the user's own account is deleted.
 *
 * Unlike deleteAllLikesForItem, the target items here are NOT being deleted
 * themselves — only this one user's like on each is going away — so their
 * like-count rows must be decremented rather than dropped.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string} userId
 * @param {string} [likeCountTableName]
 */
async function deleteAllLikesForUser(docClient, tableName, userId, likeCountTableName) {
  const result = await docClient.send(
    new QueryCommand({
      TableName: tableName,
      IndexName: 'userIndex',
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: { ':userId': userId }
    })
  )
  const likes = result.Items || []
  await batchDelete(
    docClient,
    tableName,
    likes.map((like) => ({ itemId: like.itemId, userId: like.userId }))
  )
 
  if (likeCountTableName) {
    await Promise.all(
      likes.map((like) => adjustLikeCount(docClient, likeCountTableName, like.itemId, -1))
    )
  }
}
 
// DynamoDB BatchGetItem accepts at most 100 keys per table per request.
const BATCH_GET_LIMIT = 100
 
/**
 * Batch-checks which of the given items the current user has liked (items/
 * list.js enriches a whole page of items per request). Bounded to the
 * requested itemIds, unlike entities/list.js's unbounded per-user
 * subscription query — available here because ItemLikesTable's primary key
 * already has itemId first, so a like/unlike check is a direct key lookup.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {string} tableName
 * @param {string[]} itemIds
 * @param {string} userId
 * @returns {Promise<Set<string>>}
 */
async function getLikedItemIds(docClient, tableName, itemIds, userId) {
  const uniqueIds = Array.from(new Set(itemIds)).filter(Boolean)
  const liked = new Set()
  if (uniqueIds.length === 0 || !userId) return liked
 
  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, userId })) }
        }
      })
    )
    for (const like of result.Responses?.[tableName] || []) {
      liked.add(like.itemId)
    }
  }
  return liked
}
 
module.exports = { deleteAllLikesForItem, deleteAllLikesForUser, getLikedItemIds }