All files / messages list.js

100% Statements 31/31
100% Branches 14/14
100% Functions 2/2
100% Lines 31/31

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                              1x 1x   1x 1x   1x         1x 1x   1x 9x 9x 9x 1x             8x 8x 1x             7x           6x 1x             5x 5x         5x 5x 2x 2x   1x               4x                     4x 2x                 4x                     1x 1x              
/**
 * GET /v1/conversations/{conversationId}/messages
 *
 * Paginated, chronological message history for one conversation.
 * MessagesTable's sort key is `createdAt#id` (composite string), so a plain
 * Query on `conversationId` already returns messages in time order — newest
 * page first (ScanIndexForward: false) for the common "load latest, then
 * scroll up for history" chat pattern, reversed here to chronological order
 * for display.
 *
 * Query params:
 * - limit: page size (default 30, max 100)
 * - nextToken: base64-encoded DynamoDB LastEvaluatedKey
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand, QueryCommand } = 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 = 30
const MAX_LIMIT = 100
 
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 conversationId = event.pathParameters?.conversationId
    if (!conversationId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing conversationId' })
      }
    }
 
    const participantRow = await docClient.send(
      new GetCommand({
        TableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME,
        Key: { userId, conversationId }
      })
    )
    if (!participantRow.Item) {
      return {
        statusCode: 403,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'You are not a participant in this conversation' })
      }
    }
 
    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.MESSAGES_TABLE_NAME,
        KeyConditionExpression: 'conversationId = :conversationId',
        ExpressionAttributeValues: { ':conversationId': conversationId },
        ScanIndexForward: false,
        Limit: limit,
        ExclusiveStartKey: exclusiveStartKey
      })
    )
 
    const messages = (result.Items || [])
      .map((item) => ({
        id: item.id,
        conversationId: item.conversationId,
        senderId: item.senderId,
        body: item.body,
        createdAt: item.createdAt
      }))
      .reverse()
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({
        messages,
        nextToken: result.LastEvaluatedKey
          ? Buffer.from(JSON.stringify(result.LastEvaluatedKey)).toString('base64')
          : null
      })
    }
  } catch (error) {
    console.error('[messages/list] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to list messages' })
    }
  }
}