All files / comments list.js

100% Statements 54/54
95.12% Branches 39/41
100% Functions 8/8
100% Lines 51/51

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                                                            2x 2x           2x             2x 2x 2x 2x   2x 2x     2x                 4x 4x 4x 16x     16x 16x 1x   15x 15x   3x         8x                   8x     2x 47x 47x 47x 38x 38x   38x 38x 1x     37x 37x       37x     37x 37x 5x       5x       35x 35x                                 34x       34x 34x     23x 21x               34x   34x       8x         15x           1x 1x      
/**
 * GET /v1/entities/{entityId}/items/{itemId}/comments
 * GET /v1/store/{packId}/comments
 *
 * Paginated list of the publicly visible comments of an item, or of a store
 * pack (see utils/commentAccess.js for the thread): the top-level
 * comments, or, with `?parentId=`, the replies of one comment. Only approved
 * comments (and tombstones of deleted comments that still have replies) are
 * returned — a Query on the sparse `approvedIndex`, so nothing is filtered
 * out after being read. Top-level comments come newest first, replies oldest
 * first (conversation order).
 *
 * Query params:
 * - parentId: list the replies of this comment instead of the top level
 * - limit: page size (default 20, max 50)
 * - nextToken: opaque cursor returned by the previous page
 * - withAncestors: with `parentId`, also return the chain of comments above
 *   the replies (`ancestors`, root first), so a reply can be read in its
 *   thread — used by the moderation review card's "See the discussion"
 *
 * The response also says whether the caller is `blocked` from commenting on
 * this entity or pack, so the UI can offer no composer to somebody who would be
 * refused, and, on a moderated thread, lists the caller's own comments on it that are
 * still `pending` or were `rejected` (`mine`) — invisible to everybody else,
 * the entity's owners and platform admins included: the community alone
 * decides them.
 *
 * @implements UC-COMMENT-004.1, UC-MOD-001.1, UC-MOD-010.1, UC-MOD-002.1, UC-STORE-009.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const {
  resolveCommentContext,
  isBlockedFromCommenting,
  errorResponse,
  CORS_HEADERS
} = require('../utils/commentAccess')
const {
  COMMENT_STATUS,
  approvedParentKey,
  encodeCommentsToken,
  decodeCommentsToken,
  toPublicComment
} = require('../utils/comments')
const { resolvePublicUsers } = require('../utils/userFollows')
const { isValidUuid } = require('../utils/isValidUuid')
const { COMMENTS_DEFAULT_PAGE_SIZE, COMMENTS_MAX_PAGE_SIZE } = require('../utils/constants')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
/** Most ancestors returned by `?withAncestors=true`: replies nest without limit, reads must not. */
const MAX_ANCESTORS = 10
 
/**
 * The comments above `parentId`, root first, `parentId` included: one read by
 * primary key per level, at most MAX_ANCESTORS. Only publicly visible comments
 * (approved, or tombstones) are returned: the walk stops at anything else.
 * `truncated` says the chain goes higher than what was read.
 */
async function loadAncestors(itemId, parentId) {
  const ancestors = []
  let nextId = parentId
  while (nextId && ancestors.length < MAX_ANCESTORS) {
    const result = await docClient.send(
      new GetCommand({ TableName: process.env.COMMENTS_TABLE_NAME, Key: { itemId, id: nextId } })
    )
    const row = result.Item
    if (!row || (row.status !== COMMENT_STATUS.APPROVED && row.status !== COMMENT_STATUS.DELETED)) {
      return { ancestors, truncated: false }
    }
    ancestors.unshift(row)
    nextId = row.parentId ?? null
  }
  return { ancestors, truncated: !!nextId }
}
 
/** The caller's comments on an item that are awaiting review or were rejected (bounded page). */
async function listUnapprovedOwnComments(userId, itemId) {
  const result = await docClient.send(
    new QueryCommand({
      TableName: process.env.COMMENTS_TABLE_NAME,
      IndexName: 'unapprovedIndex',
      KeyConditionExpression: 'unapprovedKey = :key',
      ExpressionAttributeValues: { ':key': `${userId}#${itemId}` },
      ScanIndexForward: false,
      Limit: COMMENTS_MAX_PAGE_SIZE
    })
  )
  return result.Items || []
}
 
exports.handler = async (event) => {
  try {
    const context = await resolveCommentContext(docClient, event)
    if (context.response) return context.response
    const { auth, thread } = context
    const itemId = thread.key
 
    const parentId = event.queryStringParameters?.parentId || null
    if (parentId && !isValidUuid(parentId)) {
      return errorResponse(400, 'Invalid parentId')
    }
 
    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
 
    const partitionKey = approvedParentKey(itemId, parentId)
 
    let exclusiveStartKey
    const nextToken = event.queryStringParameters?.nextToken
    if (nextToken) {
      exclusiveStartKey = decodeCommentsToken(nextToken, {
        itemId,
        approvedParentKey: partitionKey
      })
      if (!exclusiveStartKey) return errorResponse(400, 'Invalid nextToken')
    }
 
    const withAncestors =
      !!parentId && !nextToken && event.queryStringParameters?.withAncestors === 'true'
    const [result, chain] = await Promise.all([
      docClient.send(
        new QueryCommand({
          TableName: process.env.COMMENTS_TABLE_NAME,
          IndexName: 'approvedIndex',
          KeyConditionExpression: 'approvedParentKey = :key',
          ExpressionAttributeValues: { ':key': partitionKey },
          ScanIndexForward: parentId !== null,
          Limit: limit,
          ExclusiveStartKey: exclusiveStartKey
        })
      ),
      withAncestors
        ? loadAncestors(itemId, parentId)
        : Promise.resolve({ ancestors: [], truncated: false })
    ])
 
    const rows = result.Items || []
    // On a moderated thread the caller's own comments that are not visible yet
    // (awaiting review, or rejected) come with the first page of top-level
    // comments: one Query on a sparse index, nothing to filter out.
    const wantsMine = thread.moderated && !parentId && !nextToken
    const [authors, blocked, mineRows] = await Promise.all([
      resolvePublicUsers(docClient, process.env.USERS_TABLE_NAME, [
        ...[...rows, ...chain.ancestors]
          .filter((row) => row.status !== 'deleted')
          .map((row) => row.authorId),
        // the caller, for their own not-yet-visible comments (`mine` below)
        ...(wantsMine ? [auth.userId] : [])
      ]),
      // Lets the panel hide the composer up front instead of after a refused post
      isBlockedFromCommenting(docClient, thread.blocksKey, auth.userId),
      wantsMine ? listUnapprovedOwnComments(auth.userId, itemId) : Promise.resolve([])
    ])
    const mine = mineRows.map((row) => toPublicComment(row, authors.get(row.authorId)))
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({
        comments: rows.map((row) => toPublicComment(row, authors.get(row.authorId))),
        nextToken: encodeCommentsToken(result.LastEvaluatedKey),
        blocked,
        mine,
        ...(withAncestors && {
          ancestors: chain.ancestors.map((row) => toPublicComment(row, authors.get(row.authorId))),
          ancestorsTruncated: chain.truncated
        })
      })
    }
  } catch (error) {
    console.error('[comments/list] Exception:', error.message, error.stack)
    return errorResponse(500, 'Failed to list comments')
  }
}