All files / conversations list.js

100% Statements 47/47
100% Branches 28/28
100% Functions 6/6
100% Lines 43/43

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                                          1x 1x   1x 1x   1x         1x 1x 1x   1x           8x 8x   4x 4x 4x 4x     4x       4x   4x     1x 12x 12x 12x 1x             11x 11x 11x 1x             10x 10x         10x 10x 2x 2x   1x               9x                       8x 8x   8x 4x 4x                           8x                     1x 1x              
/**
 * GET /v1/conversations
 *
 * The caller's DM inbox, sorted by most recent activity, via
 * ConversationParticipantsTable's `recencyIndex` GSI (PK userId, SK
 * lastMessageAt) — the base table's own sort key (conversationId) doesn't
 * provide that ordering. Message requests the caller received and hasn't
 * accepted carry no `lastMessageAt`, so they are absent from that index:
 * `folder=requests` lists them instead, from the sparse `requestsIndex`
 * (SK requestedAt). Each row already denormalizes
 * `otherUserId`/`lastMessagePreview`/`unreadCount`, so the only extra lookup
 * needed is batch-resolving each `otherUserId` to a nickname.
 *
 * Query params:
 * - folder: 'inbox' (default) or 'requests'
 * - limit: page size (default 20, max 100)
 * - nextToken: base64-encoded DynamoDB LastEvaluatedKey
 *
 * @implements UC-DM-004.2, UC-DM-007.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
const DEFAULT_LIMIT = 20
const MAX_LIMIT = 100
const BATCH_GET_LIMIT = 100
 
const FOLDERS = {
  inbox: { indexName: 'recencyIndex', sortKey: 'lastMessageAt' },
  requests: { indexName: 'requestsIndex', sortKey: 'requestedAt' }
}
 
async function batchGetUsersByIds(ids) {
  const uniqueIds = Array.from(new Set(ids)).filter(Boolean)
  if (uniqueIds.length === 0) return new Map()
 
  const users = []
  for (let offset = 0; offset < uniqueIds.length; offset += BATCH_GET_LIMIT) {
    const chunk = uniqueIds.slice(offset, offset + BATCH_GET_LIMIT)
    const result = await docClient.send(
      new BatchGetCommand({
        RequestItems: {
          [process.env.USERS_TABLE_NAME]: { Keys: chunk.map((id) => ({ id })) }
        }
      })
    )
    users.push(...(result.Responses?.[process.env.USERS_TABLE_NAME] || []))
  }
  return new Map(users.map((user) => [user.id, user]))
}
 
exports.handler = async (event) => {
  try {
    const userId = event.requestContext?.authorizer?.claims?.sub
    if (!userId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    const folderName = event.queryStringParameters?.folder || 'inbox'
    const folder = FOLDERS[folderName]
    if (!folder) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Invalid folder' })
      }
    }
 
    const rawLimit = parseInt(event.queryStringParameters?.limit, 10)
    const limit = Number.isFinite(rawLimit)
      ? Math.min(Math.max(rawLimit, 1), MAX_LIMIT)
      : DEFAULT_LIMIT
 
    let exclusiveStartKey
    const nextToken = event.queryStringParameters?.nextToken
    if (nextToken) {
      try {
        exclusiveStartKey = JSON.parse(Buffer.from(nextToken, 'base64').toString())
      } catch {
        return {
          statusCode: 400,
          headers: CORS_HEADERS,
          body: JSON.stringify({ error: 'Invalid nextToken' })
        }
      }
    }
 
    const result = await docClient.send(
      new QueryCommand({
        TableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME,
        IndexName: folder.indexName,
        KeyConditionExpression: 'userId = :userId',
        ExpressionAttributeValues: { ':userId': userId },
        ScanIndexForward: false,
        Limit: limit,
        ExclusiveStartKey: exclusiveStartKey
      })
    )
 
    const rows = result.Items || []
    const usersById = await batchGetUsersByIds(rows.map((row) => row.otherUserId))
 
    const conversations = rows.map((row) => {
      const otherUser = usersById.get(row.otherUserId)
      return {
        conversationId: row.conversationId,
        otherUserId: row.otherUserId,
        otherUserNickname: otherUser?.nickname || null,
        otherUserName: otherUser?.name || null,
        otherUserProfilePicture: otherUser?.profilePicture || null,
        lastMessageAt: row[folder.sortKey],
        lastMessagePreview: row.lastMessagePreview,
        lastMessageSenderId: row.lastMessageSenderId,
        unreadCount: row.unreadCount || 0,
        status: row.status || 'accepted'
      }
    })
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({
        conversations,
        nextToken: result.LastEvaluatedKey
          ? Buffer.from(JSON.stringify(result.LastEvaluatedKey)).toString('base64')
          : null
      })
    }
  } catch (error) {
    console.error('[conversations/list] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to list conversations' })
    }
  }
}