All files / items like.js

97.77% Statements 44/45
89.65% Branches 26/29
100% Functions 1/1
97.77% Lines 44/45

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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184                                1x         1x         1x 1x   1x 1x   1x         1x 13x 13x   13x 1x             12x 12x   12x 1x             11x               11x             10x 1x             9x 1x             8x 8x 1x             7x             7x 1x             6x             6x 1x             5x 5x             5x                 5x 5x     5x   4x   4x           2x         1x             1x 1x               1x  
/**
 * POST /v1/entities/{entityId}/items/{itemId}/like
 *
 * Like an item on behalf of the calling user, personal per-user state shown
 * as a toggleable icon + count in the UI. Unlike entities/subscribe.js
 * (which is a bare personal action needing no RBAC permission, since
 * subscribing grants no new read access), liking requires actually being
 * able to read the item — so this checks canAccessEntity() and
 * hasEntityReadPermission() (`entities-{entityId}:items:read`) the same way
 * items/get.js and items/list.js do, rather than skipping straight to a table
 * write. Like reading, liking a public entity's item needs no role and no
 * active flow (e.g. from the catalog or the home feed).
 *
 * @implements UC-ITEM-008.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  GetCommand,
  TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const {
  authenticateRequest,
  hasEntityReadPermission,
  canAccessEntity
} = require('../shared/auth-helper')
const { buildLikeCountUpdate } = require('../utils/itemLikeCount')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const likeItemHandler = async (event) => {
  try {
    const auth = await authenticateRequest(event)
 
    if (!auth || auth.error) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: auth?.error || 'Authentication required' })
      }
    }
 
    const entityId = event.pathParameters?.entityId
    const itemId = event.pathParameters?.itemId
 
    if (!entityId || !itemId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing entityId or itemId' })
      }
    }
 
    Iif (!auth.userId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Likes require a signed-in user' })
      }
    }
 
    const entityResult = await docClient.send(
      new GetCommand({
        TableName: process.env.ENTITIES_TABLE_NAME,
        Key: { id: entityId }
      })
    )
 
    if (!entityResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Entity not found' })
      }
    }
 
    if (!canAccessEntity(auth, entityResult.Item)) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Access denied to this entity' })
      }
    }
 
    const requiredPermission = `entities-${entityId}:items:read`
    if (!(await hasEntityReadPermission(auth, entityResult.Item, requiredPermission))) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: `Permission denied: ${requiredPermission} required` })
      }
    }
 
    const itemResult = await docClient.send(
      new GetCommand({
        TableName: process.env.ITEMS_TABLE_NAME,
        Key: { entityId, id: itemId }
      })
    )
 
    if (!itemResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Item not found' })
      }
    }
 
    const existingLike = await docClient.send(
      new GetCommand({
        TableName: process.env.ITEM_LIKES_TABLE_NAME,
        Key: { itemId, userId: auth.userId }
      })
    )
 
    if (existingLike.Item) {
      return {
        statusCode: 409,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Already liked this item' })
      }
    }
 
    const now = new Date().toISOString()
    const like = { itemId, userId: auth.userId, likedAt: now }
 
    // The like Put and the like-count +1 must succeed or fail together —
    // otherwise a crash between the two would leave the counter permanently
    // out of sync with the actual like rows. The ConditionExpression (rather
    // than relying solely on the pre-check Get above) also closes the race
    // where two concurrent like requests both pass that check.
    const transactItems = [
      {
        Put: {
          TableName: process.env.ITEM_LIKES_TABLE_NAME,
          Item: like,
          ConditionExpression: 'attribute_not_exists(itemId)'
        }
      }
    ]
    Eif (process.env.ITEM_LIKE_COUNT_TABLE_NAME) {
      transactItems.push(buildLikeCountUpdate(process.env.ITEM_LIKE_COUNT_TABLE_NAME, itemId, 1))
    }
 
    await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
 
    console.log('[like] Item liked:', { userId: auth.userId, entityId, itemId })
 
    return {
      statusCode: 201,
      headers: CORS_HEADERS,
      body: JSON.stringify(like)
    }
  } catch (error) {
    if (
      error.name === 'ConditionalCheckFailedException' ||
      (error.name === 'TransactionCanceledException' &&
        error.CancellationReasons?.[0]?.Code === 'ConditionalCheckFailed')
    ) {
      return {
        statusCode: 409,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Already liked this item' })
      }
    }
 
    console.error('[like] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to like item' })
    }
  }
}
 
module.exports = { likeItemHandler }