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 | 1x 1x 1x 1x 1x 1x 6x 6x 6x 1x 5x 5x 5x 6x 5x 8x 8x 5x 4x 1x 1x | /**
* GET /v1/conversations/unread-count
*
* Total unread DM count across all of the caller's conversations, message
* requests included — used by the header badge's initial load and its REST
* fallback on WebSocket (re)connect — plus `requestCount`, how many of those
* are unread message requests (a row still carrying `requestedAt`), for the
* Messages page's Requests tab. A user is expected to have at most a handful
* of conversations, so summing `unreadCount` in Lambda memory over a single
* Query is fine and avoids a separate denormalized counter table for v1.
*
* @implements UC-DM-006.1, UC-DM-007.1
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, 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': '*'
}
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' })
}
}
let count = 0
let requestCount = 0
let exclusiveStartKey
do {
const result = await docClient.send(
new QueryCommand({
TableName: process.env.CONVERSATION_PARTICIPANTS_TABLE_NAME,
KeyConditionExpression: 'userId = :userId',
ExpressionAttributeValues: { ':userId': userId },
ProjectionExpression: 'unreadCount, requestedAt',
ExclusiveStartKey: exclusiveStartKey
})
)
for (const row of result.Items || []) {
count += row.unreadCount || 0
if (row.requestedAt && row.unreadCount > 0) requestCount++
}
exclusiveStartKey = result.LastEvaluatedKey
} while (exclusiveStartKey)
return {
statusCode: 200,
headers: CORS_HEADERS,
body: JSON.stringify({ count, requestCount })
}
} catch (error) {
console.error('[conversations/unread-count] Exception:', error.message, error.stack)
return {
statusCode: 500,
headers: CORS_HEADERS,
body: JSON.stringify({ error: 'Failed to fetch unread count' })
}
}
}
|