All files / utils comments.js

96% Statements 24/25
97.87% Branches 46/47
100% Functions 6/6
96% Lines 24/25

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 14123x               23x               23x                 39x                   65x       41x                       12x 12x 10x             5x                   7x                       64x 6x   58x 58x 4x   54x 3x   51x     51x                       67x   67x 67x                                       23x                    
const { MAX_COMMENT_LENGTH, MAX_COMMENT_BODY_BYTES } = require('./constants')
 
/**
 * Comment lifecycle states. `pending` and `rejected` only exist on public
 * entities, where a comment is moderated by the community before anyone else
 * sees it. `deleted` is a tombstone kept while a comment still has visible
 * replies, so the thread stays intact — see docs/architecture/MODERATION.md.
 */
const COMMENT_STATUS = {
  PENDING: 'pending',
  APPROVED: 'approved',
  REJECTED: 'rejected',
  DELETED: 'deleted'
}
 
/** Marker used in place of a parent id for top-level comments in `approvedParentKey`. */
const ROOT_PARENT = 'ROOT'
 
/**
 * Sort key used by the GSIs (chronological order, id as tie-breaker). It is
 * an attribute, not the table's own sort key: the table is keyed itemId + id
 * so a comment can be fetched directly by its id (parent lookup, deletion,
 * moderation).
 */
function commentSortKey(createdAt, commentId) {
  return `${createdAt}#${commentId}`
}
 
/**
 * Partition key of the sparse `approvedIndex` GSI. Only comments that are
 * publicly visible (approved, or a tombstone that still has replies) carry
 * it, so a Query on it returns exactly the comments to display, one page of
 * siblings at a time (top-level comments, or the replies of one parent).
 */
function approvedParentKey(itemId, parentId) {
  return `${itemId}#${parentId || ROOT_PARENT}`
}
 
function encodeCommentsToken(lastEvaluatedKey) {
  return lastEvaluatedKey ? Buffer.from(JSON.stringify(lastEvaluatedKey)).toString('base64') : null
}
 
/**
 * Decodes a pagination token, returning null when it is malformed or was
 * minted for another list — a token is client-controlled, so it must never
 * be able to point a Query at somebody else's partition.
 *
 * @param {string} token
 * @param {{ itemId: string, approvedParentKey: string }} expected
 */
function decodeCommentsToken(token, expected) {
  try {
    const key = JSON.parse(Buffer.from(token, 'base64').toString())
    if (
      key &&
      key.itemId === expected.itemId &&
      key.approvedParentKey === expected.approvedParentKey &&
      typeof key.id === 'string' &&
      typeof key.sortKey === 'string'
    ) {
      return {
        itemId: key.itemId,
        id: key.id,
        approvedParentKey: key.approvedParentKey,
        sortKey: key.sortKey
      }
    }
  } catch {
    // fall through
  }
  return null
}
 
/**
 * Validates a comment body: a non-empty string once trimmed, at most
 * MAX_COMMENT_LENGTH characters (Unicode code points) and MAX_COMMENT_BODY_BYTES
 * bytes.
 *
 * @param {unknown} rawBody
 * @returns {{ valid: true, body: string } | { valid: false, error: string }}
 */
function validateCommentBody(rawBody) {
  if (typeof rawBody !== 'string') {
    return { valid: false, error: 'body is required' }
  }
  const body = rawBody.trim()
  if (body.length === 0) {
    return { valid: false, error: 'body is required' }
  }
  if ([...body].length > MAX_COMMENT_LENGTH) {
    return { valid: false, error: `body must be at most ${MAX_COMMENT_LENGTH} characters` }
  }
  Iif (Buffer.byteLength(body, 'utf8') > MAX_COMMENT_BODY_BYTES) {
    return { valid: false, error: 'body is too large' }
  }
  return { valid: true, body }
}
 
/**
 * Shapes a stored comment for the API, joining its author's public profile.
 * A deleted comment (tombstone) never exposes its body. An author who no
 * longer exists resolves to null fields rather than dropping the comment.
 *
 * @param {object} comment
 * @param {{ name?: string, nickname?: string|null, profilePicture?: string|null }} [author]
 */
function toPublicComment(comment, author) {
  const deleted = comment.status === COMMENT_STATUS.DELETED
  // A pack's comment has no item or entity: its thread key is the pack id
  const onPack = typeof comment.packId === 'string'
  return {
    id: comment.id,
    itemId: onPack ? null : comment.itemId,
    entityId: comment.entityId ?? null,
    packId: onPack ? comment.packId : null,
    // The version a pack's comment was written on: comments stay across versions
    packVersion: comment.packVersion ?? null,
    parentId: comment.parentId ?? null,
    authorId: deleted ? null : comment.authorId,
    authorName: deleted ? null : (author?.name ?? null),
    authorNickname: deleted ? null : (author?.nickname ?? null),
    authorProfilePicture: deleted ? null : (author?.profilePicture ?? null),
    body: deleted ? null : comment.body,
    status: comment.status,
    deleted,
    replyCount: Math.max(0, comment.replyCount || 0),
    createdAt: comment.createdAt
  }
}
 
module.exports = {
  COMMENT_STATUS,
  ROOT_PARENT,
  commentSortKey,
  approvedParentKey,
  encodeCommentsToken,
  decodeCommentsToken,
  validateCommentBody,
  toPublicComment
}