All files / utils conversationCleanup.js

100% Statements 21/21
83.33% Branches 5/6
100% Functions 5/5
100% Lines 20/20

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 942x 2x             40x   40x 41x 41x 41x   40x                         4x           4x     4x         4x                                     36x             36x     6x     36x 6x               6x 3x               2x  
const { QueryCommand, GetCommand, DeleteCommand } = require('@aws-sdk/lib-dynamodb')
const { batchDelete } = require('./batchWrite')
 
/**
 * Collects every key of a Query (paginated), projecting only the given
 * attributes.
 */
async function queryAllKeys(docClient, params) {
  const items = []
  let lastKey
  do {
    const result = await docClient.send(new QueryCommand({ ...params, ExclusiveStartKey: lastKey }))
    items.push(...(result.Items || []))
    lastKey = result.LastEvaluatedKey
  } while (lastKey)
  return items
}
 
/**
 * Deletes a conversation with all of its messages.
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ conversationsTableName: string, messagesTableName: string, conversationId: string }} params
 */
async function deleteConversation(
  docClient,
  { conversationsTableName, messagesTableName, conversationId }
) {
  const messages = await queryAllKeys(docClient, {
    TableName: messagesTableName,
    KeyConditionExpression: 'conversationId = :conversationId',
    ExpressionAttributeValues: { ':conversationId': conversationId },
    ProjectionExpression: 'conversationId, sortKey'
  })
  await batchDelete(
    docClient,
    messagesTableName,
    messages.map((message) => ({
      conversationId: message.conversationId,
      sortKey: message.sortKey
    }))
  )
  await docClient.send(
    new DeleteCommand({ TableName: conversationsTableName, Key: { id: conversationId } })
  )
}
 
/**
 * Removes a deleted user from the messaging tables: their own inbox rows
 * (ConversationParticipantsTable) always go. A conversation itself, with its
 * messages, only goes once no participant row is left — while the other
 * participant still has it, they keep their history (conversations/list.js
 * already renders a vanished counterpart as null nickname/name/picture).
 *
 * @param {import('@aws-sdk/lib-dynamodb').DynamoDBDocumentClient} docClient
 * @param {{ participantsTableName: string, conversationsTableName: string, messagesTableName: string, userId: string }} params
 */
async function deleteAllConversationsForUser(
  docClient,
  { participantsTableName, conversationsTableName, messagesTableName, userId }
) {
  const rows = await queryAllKeys(docClient, {
    TableName: participantsTableName,
    KeyConditionExpression: 'userId = :userId',
    ExpressionAttributeValues: { ':userId': userId },
    ProjectionExpression: 'userId, conversationId, otherUserId'
  })
 
  await batchDelete(
    docClient,
    participantsTableName,
    rows.map((row) => ({ userId: row.userId, conversationId: row.conversationId }))
  )
 
  for (const row of rows) {
    const counterpart = row.otherUserId
      ? await docClient.send(
          new GetCommand({
            TableName: participantsTableName,
            Key: { userId: row.otherUserId, conversationId: row.conversationId }
          })
        )
      : { Item: undefined }
    if (counterpart.Item) continue
    await deleteConversation(docClient, {
      conversationsTableName,
      messagesTableName,
      conversationId: row.conversationId
    })
  }
}
 
module.exports = { deleteConversation, deleteAllConversationsForUser }