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 185 186 187 188 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 9x 23x 23x 6x 6x 5x 6x 2x 2x 36x 36x 36x 35x 35x 35x 35x 1x 34x 34x 34x 4x 30x 13x 5x 8x 3x 22x 22x 22x 22x 5x 17x 17x 4x 17x 17x 17x 17x 14x 3x 3x 1x 2x 15x 4x 4x 1x 19x 3x 3x | /**
* DELETE /v1/entities/{entityId}/items/{itemId}/comments/{commentId}
* DELETE /v1/store/{packId}/comments/{commentId}
*
* Deletes a comment. Its author may, and so may the managers of the entity
* (`entities-{id}:update` in the owning flow) or of the pack (those who may
* delete it) and platform admins — see utils/commentAccess.js — but only an
* approved comment: one awaiting review, or
* rejected, is the community's to decide and stays invisible to anybody but
* its author. A comment without visible replies is removed. One that still has
* replies becomes a tombstone — body and author erased, status `deleted` — so
* the replies stay attached to something. Either way the item's comment counter
* drops by one when the comment was counted (approved), and a removed reply
* decrements its parent's reply counter. A tombstone left without replies has
* nothing left to hold and is removed in turn, up the thread.
*
* Deleting stays possible after the entity or pack switched comments off, since a
* user must always be able to retract what they wrote.
*
* @implements UC-COMMENT-005.1, UC-COMMENT-006.1, UC-STORE-009.1
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
DynamoDBDocumentClient,
GetCommand,
TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { resolveCommentContext, errorResponse, CORS_HEADERS } = require('../utils/commentAccess')
const { COMMENT_STATUS } = require('../utils/comments')
const { buildCommentCountUpdate } = require('../utils/commentCount')
const { removeEmptyTombstones } = require('../utils/commentCleanup')
const { isValidUuid } = require('../utils/isValidUuid')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
/** Removes the comment's text and author but keeps it in place so its replies remain visible. */
function buildTombstoneUpdate(itemId, commentId) {
return {
Update: {
TableName: process.env.COMMENTS_TABLE_NAME,
Key: { itemId, id: commentId },
UpdateExpression: 'SET #status = :deleted REMOVE #body, authorId',
ConditionExpression: '#status = :approved',
ExpressionAttributeNames: { '#status': 'status', '#body': 'body' },
ExpressionAttributeValues: {
':deleted': COMMENT_STATUS.DELETED,
':approved': COMMENT_STATUS.APPROVED
}
}
}
}
function isCanceled(error) {
return error.name === 'TransactionCanceledException'
}
/**
* Runs `transactItems`. A counter update (the trailing items) failing its
* floor condition must not block the deletion itself: the row is still
* removed and the drifted counter left alone.
*/
async function sendWithCounterFallback(transactItems, coreItemCount) {
try {
await docClient.send(new TransactWriteCommand({ TransactItems: transactItems }))
} catch (error) {
const reasons = error.CancellationReasons || []
const coreFailed = reasons
.slice(0, coreItemCount)
.some((r) => r?.Code === 'ConditionalCheckFailed')
if (!isCanceled(error) || coreFailed) throw error
await docClient.send(
new TransactWriteCommand({ TransactItems: transactItems.slice(0, coreItemCount) })
)
}
}
exports.handler = async (event) => {
try {
const context = await resolveCommentContext(docClient, event, { requireEnabled: false })
if (context.response) return context.response
const { auth, thread } = context
const itemId = thread.key
const commentId = event.pathParameters?.commentId
if (!commentId || !isValidUuid(commentId)) {
return errorResponse(400, 'Invalid commentId')
}
const commentResult = await docClient.send(
new GetCommand({
TableName: process.env.COMMENTS_TABLE_NAME,
Key: { itemId, id: commentId }
})
)
const comment = commentResult.Item
if (!comment || !thread.owns(comment) || comment.status === COMMENT_STATUS.DELETED) {
return errorResponse(404, 'Comment not found')
}
// The author may always retract their comment; managers of the entity or
// pack (and platform admins) may remove anyone's.
if (comment.authorId !== auth.userId) {
if (!(await thread.canManage())) {
return errorResponse(403, 'Only the author or a manager can delete this comment')
}
// A comment not approved yet is invisible to anybody but its author: it
// is not theirs to remove before the community decided it.
if (comment.status !== COMMENT_STATUS.APPROVED) {
return errorResponse(404, 'Comment not found')
}
}
const wasCounted = comment.status === COMMENT_STATUS.APPROVED
const countUpdate = buildCommentCountUpdate(
process.env.ITEM_COMMENT_COUNT_TABLE_NAME,
itemId,
-1
)
const hasReplies = (comment.replyCount || 0) > 0
if (wasCounted && hasReplies) {
await sendWithCounterFallback([buildTombstoneUpdate(itemId, commentId), countUpdate], 1)
} else {
const removeItems = [
{
Delete: {
TableName: process.env.COMMENTS_TABLE_NAME,
Key: { itemId, id: commentId },
// A reply may land between the read above and this write: then
// the comment must become a tombstone instead of orphaning it.
ConditionExpression:
'attribute_exists(id) AND (attribute_not_exists(replyCount) OR replyCount = :zero)',
ExpressionAttributeValues: { ':zero': 0 }
}
}
]
if (wasCounted && comment.parentId) {
removeItems.push({
Update: {
TableName: process.env.COMMENTS_TABLE_NAME,
Key: { itemId, id: comment.parentId },
UpdateExpression: 'ADD replyCount :minusOne',
ConditionExpression: 'replyCount >= :one',
ExpressionAttributeValues: { ':minusOne': -1, ':one': 1 }
}
})
}
// Order matters: the counter must be last, see isCountFloorCancellation.
if (wasCounted) removeItems.push(countUpdate)
let removed = false
try {
await sendWithCounterFallback(removeItems, 1)
removed = true
} catch (error) {
const reasons = error.CancellationReasons || []
if (isCanceled(error) && reasons[0]?.Code === 'ConditionalCheckFailed' && wasCounted) {
// A reply arrived meanwhile: keep the thread, tombstone the comment.
await sendWithCounterFallback([buildTombstoneUpdate(itemId, commentId), countUpdate], 1)
} else {
throw error
}
}
if (removed && wasCounted && comment.parentId) {
try {
await removeEmptyTombstones(
docClient,
process.env.COMMENTS_TABLE_NAME,
itemId,
comment.parentId
)
} catch (error) {
// The comment is deleted already: a tombstone left behind is harmless
console.error('[comments/delete] Tombstone cleanup failed:', error.message)
}
}
}
return { statusCode: 204, headers: CORS_HEADERS, body: '' }
} catch (error) {
console.error('[comments/delete] Exception:', error.message, error.stack)
return errorResponse(500, 'Failed to delete comment')
}
}
|