All files / store unlike.js

100% Statements 28/28
100% Branches 10/10
100% Functions 1/1
100% Lines 26/26

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                  1x 1x         1x 1x 1x 1x 1x   1x   1x 6x 6x 6x 5x   5x 5x   4x               4x 4x           3x 1x 2x       1x   1x       2x   1x 1x      
/**
 * DELETE /v1/store/{packId}/like
 *
 * Removes the caller's like. Removing the like row must not fail because the
 * counter already sits at its floor: the transaction is then retried without it.
 *
 * @implements UC-STORE-006.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, TransactWriteCommand } = require('@aws-sdk/lib-dynamodb')
const {
  authenticateModerator: authenticateUser,
  errorResponse,
  jsonResponse
} = require('../utils/moderation/access')
const { likesTable } = require('../utils/packs')
const { buildPackLikesCountUpdate } = require('../utils/packCleanup')
const { isCountFloorCancellation } = require('../utils/counterFloor')
const { isValidUuid } = require('../utils/isValidUuid')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
exports.handler = async (event) => {
  try {
    const caller = await authenticateUser(event)
    if (caller.response) return caller.response
    const { userId } = caller.auth
 
    const packId = event.pathParameters?.packId
    if (!isValidUuid(packId)) return errorResponse(404, 'Pack not found')
 
    const deleteLike = {
      Delete: {
        TableName: likesTable(),
        Key: { packId, userId },
        ConditionExpression: 'attribute_exists(packId)'
      }
    }
 
    try {
      await docClient.send(
        new TransactWriteCommand({
          TransactItems: [deleteLike, { Update: buildPackLikesCountUpdate(packId, -1) }]
        })
      )
    } catch (error) {
      if (isCountFloorCancellation(error)) {
        await docClient.send(new TransactWriteCommand({ TransactItems: [deleteLike] }))
      } else if (
        error.name === 'TransactionCanceledException' &&
        error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed'
      ) {
        return errorResponse(404, 'Like not found')
      } else {
        throw error
      }
    }
 
    return jsonResponse(200, { packId, likedByMe: false })
  } catch (error) {
    console.error('[store/unlike] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to unlike pack')
  }
}