All files / comments list-blocks.js

100% Statements 31/31
95% Branches 19/20
100% Functions 3/3
100% Lines 30/30

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                              2x 2x 2x 2x 2x   2x 2x   2x 13x 13x 13x 11x   11x 11x         11x 11x 3x 3x   2x 1x 1x   2x       9x                   8x 8x     4x     8x       4x                         1x 1x      
/**
 * GET /v1/entities/{entityId}/comment-blocks
 * GET /v1/store/{packId}/comment-blocks
 *
 * The users blocked from commenting on an entity or a pack, newest block first,
 * paginated, joined with their public profile. Only its managers and platform
 * admins may see it.
 *
 * Query params:
 * - limit: page size (default 20, max 50)
 * - nextToken: opaque cursor returned by the previous page
 *
 * @implements UC-COMMENT-007.1, UC-STORE-009.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { resolveManagerContext, errorResponse, CORS_HEADERS } = require('../utils/commentAccess')
const { resolvePublicUsers } = require('../utils/userFollows')
const { COMMENTS_DEFAULT_PAGE_SIZE, COMMENTS_MAX_PAGE_SIZE } = require('../utils/constants')
 
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 { blocksKey } = context
 
    const rawLimit = parseInt(event.queryStringParameters?.limit, 10)
    const limit = Number.isFinite(rawLimit)
      ? Math.min(Math.max(rawLimit, 1), COMMENTS_MAX_PAGE_SIZE)
      : COMMENTS_DEFAULT_PAGE_SIZE
 
    let exclusiveStartKey
    const nextToken = event.queryStringParameters?.nextToken
    if (nextToken) {
      try {
        const key = JSON.parse(Buffer.from(nextToken, 'base64').toString())
        // A client-controlled cursor must not point the Query at another entity or pack
        if (key?.entityId !== blocksKey || typeof key.userId !== 'string')
          throw new Error('bad key')
        exclusiveStartKey = { entityId: key.entityId, userId: key.userId }
      } catch {
        return errorResponse(400, 'Invalid nextToken')
      }
    }
 
    const result = await docClient.send(
      new QueryCommand({
        TableName: process.env.COMMENT_BLOCKS_TABLE_NAME,
        KeyConditionExpression: 'entityId = :entityId',
        ExpressionAttributeValues: { ':entityId': blocksKey },
        Limit: limit,
        ExclusiveStartKey: exclusiveStartKey
      })
    )
 
    const rows = result.Items || []
    const users = await resolvePublicUsers(
      docClient,
      process.env.USERS_TABLE_NAME,
      rows.map((row) => row.userId)
    )
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({
        blocks: rows.map((row) => ({
          userId: row.userId,
          name: users.get(row.userId)?.name ?? null,
          nickname: users.get(row.userId)?.nickname ?? null,
          profilePicture: users.get(row.userId)?.profilePicture ?? null,
          createdAt: row.createdAt
        })),
        nextToken: result.LastEvaluatedKey
          ? Buffer.from(JSON.stringify(result.LastEvaluatedKey)).toString('base64')
          : null
      })
    }
  } catch (error) {
    console.error('[comments/list-blocks] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to list blocked users')
  }
}