All files / users list-subscriptions.js

97.95% Statements 48/49
62.5% Branches 10/16
100% Functions 10/10
97.77% Lines 44/45

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                                1x 1x 1x   1x 1x   1x           1x     2x 2x   1x 1x 1x 1x     2x       1x   1x       3x   3x 3x 2x 2x   2x     1x 4x 4x   4x 1x             3x         2x   2x   2x   2x   2x 2x 2x 2x     2x             2x 2x   2x           2x           1x 1x               1x  
/**
 * GET /v1/users/me/subscriptions
 *
 * Lists the public entities the calling user is subscribed to (see
 * entities/subscribe.js) — shown on their own profile page. Self only: there
 * is no {userId} variant, since a user's entity subscriptions are personal
 * and not exposed on anyone else's profile.
 *
 * Unlike GET /v1/catalog, this does not return every public entity with a
 * `subscribedByCurrentUser` flag — it returns only the ones actually
 * subscribed to, so it stays a small, purpose-built profile widget instead of
 * dragging in the catalog's search/sort/fork/link concerns.
 *
 * @implements UC-PROFILE-008.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, BatchGetCommand } = require('@aws-sdk/lib-dynamodb')
const { getSubscriberCounts } = require('../utils/entitySubscriberCount')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
const CORS_HEADERS = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*'
}
 
// DynamoDB BatchGetItem accepts at most 100 keys per table per request.
const BATCH_GET_LIMIT = 100
 
async function batchGetByIds(tableName, ids) {
  const uniqueIds = Array.from(new Set(ids)).filter(Boolean)
  if (uniqueIds.length === 0) return []
 
  const items = []
  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: {
          [tableName]: { Keys: chunk.map((id) => ({ id })) }
        }
      })
    )
    items.push(...(result.Responses?.[tableName] || []))
  }
  return items
}
 
async function queryAllPages(queryParams) {
  const items = []
  let ExclusiveStartKey
  do {
    const result = await docClient.send(new QueryCommand({ ...queryParams, ExclusiveStartKey }))
    items.push(...(result.Items || []))
    ExclusiveStartKey = result.LastEvaluatedKey
  } while (ExclusiveStartKey)
  return items
}
 
const listUserSubscriptionsHandler = async (event) => {
  try {
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    if (!userId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    const subscriptions = await queryAllPages({
      TableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
      KeyConditionExpression: 'userId = :userId',
      ExpressionAttributeValues: { ':userId': userId }
    })
    subscriptions.sort((a, b) => (b.subscribedAt || '').localeCompare(a.subscribedAt || ''))
 
    const entities = await batchGetByIds(
      process.env.ENTITIES_TABLE_NAME,
      subscriptions.map((s) => s.entityId)
    )
    const entityById = new Map(entities.map((entity) => [entity.id, entity]))
 
    let subscriberCounts = new Map()
    Eif (process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME) {
      try {
        subscriberCounts = await getSubscriberCounts(
          docClient,
          process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME,
          entities.map((entity) => entity.id)
        )
      } catch (subscriberCountErr) {
        console.error('[list-subscriptions] Error fetching subscriber counts:', subscriberCountErr)
      }
    }
 
    const items = subscriptions
      .map((s) => entityById.get(s.entityId))
      .filter(Boolean)
      .map((entity) => ({
        ...entity,
        subscribedByCurrentUser: true,
        subscriberCount: subscriberCounts.get(entity.id) ?? 0
      }))
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({ items, total: items.length })
    }
  } catch (error) {
    console.error('[list-subscriptions] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Failed to list subscriptions' })
    }
  }
}
 
module.exports = { listUserSubscriptionsHandler }