All files / comments block.js

100% Statements 27/27
100% Branches 10/10
100% Functions 1/1
100% Lines 23/23

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                          2x 2x 2x   2x 2x   2x 15x 15x 15x 9x   9x 9x 8x   7x     7x   6x           6x 1x     5x           5x       4x   1x 1x      
/**
 * PUT /v1/entities/{entityId}/comment-blocks/{userId}
 * PUT /v1/store/{packId}/comment-blocks/{userId}
 *
 * Blocks a user from commenting on an entity, or on a pack. Only managers of
 * the entity (`entities-{id}:update` in its flow) or of the pack (those who may
 * delete it) and platform admins may. A block stops commenting and nothing
 * else: the blocked user keeps every other right on the entity or pack, including reviewing comments in the moderation queue, and their
 * existing comments stay. Idempotent.
 *
 * @implements UC-COMMENT-007.1, UC-STORE-009.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, PutCommand } = require('@aws-sdk/lib-dynamodb')
const { resolveManagerContext, errorResponse, CORS_HEADERS } = require('../utils/commentAccess')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
exports.handler = async (event) => {
  try {
    const context = await resolveManagerContext(docClient, event)
    if (context.response) return context.response
    const { auth, blocksKey } = context
 
    const targetUserId = event.pathParameters?.userId
    if (!targetUserId) return errorResponse(400, 'Missing userId')
    if (targetUserId === auth.userId) return errorResponse(400, 'You cannot block yourself')
 
    const target = await docClient.send(
      new GetCommand({ TableName: process.env.USERS_TABLE_NAME, Key: { id: targetUserId } })
    )
    if (!target.Item) return errorResponse(404, 'User not found')
 
    const existing = await docClient.send(
      new GetCommand({
        TableName: process.env.COMMENT_BLOCKS_TABLE_NAME,
        Key: { entityId: blocksKey, userId: targetUserId }
      })
    )
    if (existing.Item) {
      return { statusCode: 200, headers: CORS_HEADERS, body: JSON.stringify(existing.Item) }
    }
 
    const block = {
      entityId: blocksKey,
      userId: targetUserId,
      blockedBy: auth.userId,
      createdAt: new Date().toISOString()
    }
    await docClient.send(
      new PutCommand({ TableName: process.env.COMMENT_BLOCKS_TABLE_NAME, Item: block })
    )
 
    return { statusCode: 200, headers: CORS_HEADERS, body: JSON.stringify(block) }
  } catch (error) {
    console.error('[comments/block] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to block user')
  }
}