All files / users list-public-entities.js

93.75% Statements 45/48
70% Branches 14/20
87.5% Functions 7/8
95.55% Lines 43/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 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 152 153 154 155                                    1x 1x 1x   1x 1x   1x           6x   6x 6x 5x 5x   5x       2x     1x 6x 6x 6x   6x 1x             5x 1x             4x           4x 1x             3x             2x   1x               2x 2x   2x 2x 2x         2x         2x 2x 2x 2x     1x                   2x                   2x           1x 1x               1x  
/**
 * GET /v1/users/{userId}/entities
 *
 * Lists the public entities owned by {userId}, across every flow they own.
 * Entities belong to a flowId, not directly a userId, so this resolves the
 * user's owned flow(s) via FlowsTable.ownerIndex first, then each flow's
 * public entities via EntitiesTable.flowIndex — the same visibility rule
 * catalog/list.js uses (visibility === 'public', with the same legacy
 * isPublic === 'true' fallback), just scoped to one owner's flows instead of
 * the whole platform, so none of catalog/list.js's platform-wide
 * search/sort/pagination machinery is needed here.
 *
 * No pagination: a single user's owned public-entity count is expected to be
 * small (unlike the platform-wide catalog), unlike GET /v1/catalog.
 *
 * @implements UC-PROFILE-009.1
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, GetCommand } = 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': '*'
}
 
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
}
 
function isPublicEntity(entity) {
  return entity.visibility === 'public' || entity.isPublic === 'true'
}
 
const listUserPublicEntitiesHandler = async (event) => {
  try {
    const userId = event.pathParameters?.userId
    const currentUserId = event.requestContext?.authorizer?.claims?.sub
 
    if (!currentUserId) {
      return {
        statusCode: 401,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Unauthorized' })
      }
    }
 
    if (!userId) {
      return {
        statusCode: 400,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'Missing user id' })
      }
    }
 
    const userResult = await docClient.send(
      new GetCommand({
        TableName: process.env.USERS_TABLE_NAME,
        Key: { id: userId }
      })
    )
    if (!userResult.Item) {
      return {
        statusCode: 404,
        headers: CORS_HEADERS,
        body: JSON.stringify({ error: 'User not found' })
      }
    }
 
    const ownedFlows = await queryAllPages({
      TableName: process.env.FLOWS_TABLE_NAME,
      IndexName: 'ownerIndex',
      KeyConditionExpression: 'ownerId = :userId',
      ExpressionAttributeValues: { ':userId': userId }
    })
 
    const entitiesByFlow = await Promise.all(
      ownedFlows.map((flow) =>
        queryAllPages({
          TableName: process.env.ENTITIES_TABLE_NAME,
          IndexName: 'flowIndex',
          KeyConditionExpression: 'flowId = :flowId',
          ExpressionAttributeValues: { ':flowId': flow.id }
        })
      )
    )
    const flowSlugByFlowId = new Map(ownedFlows.map((flow) => [flow.id, flow.slug || null]))
    const publicEntities = entitiesByFlow.flat().filter(isPublicEntity)
 
    let subscribedEntityIds = new Set()
    try {
      const subscriptions = await queryAllPages({
        TableName: process.env.ENTITY_SUBSCRIPTIONS_TABLE_NAME,
        KeyConditionExpression: 'userId = :userId',
        ExpressionAttributeValues: { ':userId': currentUserId }
      })
      subscribedEntityIds = new Set(subscriptions.map((s) => s.entityId))
    } catch (subscriptionErr) {
      console.error('[list-public-entities] Error fetching subscriptions:', subscriptionErr)
    }
 
    let subscriberCounts = new Map()
    Eif (process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME) {
      try {
        subscriberCounts = await getSubscriberCounts(
          docClient,
          process.env.ENTITY_SUBSCRIBER_COUNT_TABLE_NAME,
          publicEntities.map((entity) => entity.id)
        )
      } catch (subscriberCountErr) {
        console.error(
          '[list-public-entities] Error fetching subscriber counts:',
          subscriberCountErr
        )
      }
    }
 
    const items = publicEntities.map((entity) => ({
      ...entity,
      visibility: 'public',
      subscribedByCurrentUser: subscribedEntityIds.has(entity.id),
      subscriberCount: subscriberCounts.get(entity.id) ?? 0,
      ownerId: userId,
      ownerNickname: userResult.Item.nickname || null,
      flowSlug: flowSlugByFlowId.get(entity.flowId) ?? null
    }))
 
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({ items, total: items.length })
    }
  } catch (error) {
    console.error('[list-public-entities] Exception:', error.message, error.stack)
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: "Failed to list user's public entities" })
    }
  }
}
 
module.exports = { listUserPublicEntitiesHandler }