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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | 1x 1x 1x 1x 1x 1x 1x 5x 7x 4x 4x 7x 6x 5x 7x 7x 4x 4x 4x 4x 4x 4x 4x 4x 13x 4x 3x 1x 2x 2x 1x 1x 1x 9x 9x 9x 1x 8x 8x 8x 8x 8x 8x 1x 1x 1x 7x 8x 6x 6x 1x 3x 3x 6x 6x 6x 6x 6x 5x 5x 5x 5x 6x 6x 6x 5x 1x 1x 6x 1x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x | /**
* GET /v1/catalog
*
* List all public entities from all flows, except those in the current flow
* (which are already visible in GET /v1/entities).
*
* Returns entities with additional metadata:
* - sourceFlowId: The flow that owns this entity
* - sourceFlowName: The flow name (for display)
* - forkedByCurrentFlow: boolean — true if current flow has forked this entity
*
* Query params:
* - limit: page size (default 30, max 100)
* - nextToken: pagination token (base64-encoded offset)
* - search: optional full-text search on entity name
*
* @implements UC-CATALOG-001.1, UC-CATALOG-002.1, UC-CATALOG-003.1, UC-CATALOG-004.1
*/
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, GetCommand } = require('@aws-sdk/lib-dynamodb')
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const ENTITIES_TABLE = process.env.ENTITIES_TABLE_NAME || 'EntitiesTable'
const FLOWS_TABLE = process.env.FLOWS_TABLE_NAME || 'FlowsTable'
const ENTITY_LINKS_TABLE = process.env.ENTITY_LINKS_TABLE_NAME || 'EntityLinksTable'
function isMissingIndexError(error, indexName) {
return (
error?.name === 'ValidationException' &&
typeof error?.message === 'string' &&
error.message.includes(indexName)
)
}
async function queryPublicEntitiesByVisibility() {
const result = await docClient.send(
new QueryCommand({
TableName: ENTITIES_TABLE,
IndexName: 'visibilityIndex',
KeyConditionExpression: '#visibility = :publicVisibility',
ExpressionAttributeNames: { '#visibility': 'visibility' },
ExpressionAttributeValues: { ':publicVisibility': 'public' },
Limit: 1000
})
)
return result.Items || []
}
async function queryPublicEntitiesByLegacyVisibilityValue() {
const result = await docClient.send(
new QueryCommand({
TableName: ENTITIES_TABLE,
IndexName: 'visibilityIndex',
KeyConditionExpression: '#visibility = :legacyPublicVisibility',
ExpressionAttributeNames: { '#visibility': 'visibility' },
ExpressionAttributeValues: { ':legacyPublicVisibility': 'true' },
Limit: 1000
})
)
return (result.Items || []).map((entity) => ({
...entity,
visibility: 'public'
}))
}
async function queryPublicEntitiesLegacy() {
const result = await docClient.send(
new QueryCommand({
TableName: ENTITIES_TABLE,
IndexName: 'publicIndex',
KeyConditionExpression: '#isPublic = :isPublicTrue',
ExpressionAttributeNames: { '#isPublic': 'isPublic' },
ExpressionAttributeValues: { ':isPublicTrue': 'true' },
Limit: 1000
})
)
return (result.Items || []).map((entity) => ({
...entity,
visibility: entity.visibility || 'public'
}))
}
async function getPublicEntities() {
try {
const canonical = await queryPublicEntitiesByVisibility()
// Compatibility for transitional records where visibility was set to
// "true" instead of the canonical "public" value.
let legacyVisibility = []
try {
legacyVisibility = await queryPublicEntitiesByLegacyVisibilityValue()
} catch (legacyVisibilityError) {
if (!isMissingIndexError(legacyVisibilityError, 'visibilityIndex')) {
throw legacyVisibilityError
}
}
// Best effort legacy merge for environments where some records still only
// have isPublic populated.
let legacy = []
try {
legacy = await queryPublicEntitiesLegacy()
} catch (legacyError) {
if (!isMissingIndexError(legacyError, 'publicIndex')) {
throw legacyError
}
}
const mergedById = new Map()
for (const entity of [...canonical, ...legacyVisibility, ...legacy]) {
mergedById.set(entity.id, {
...entity,
visibility: entity.visibility || (entity.isPublic === 'true' ? 'public' : 'flow-members')
})
}
return Array.from(mergedById.values())
} catch (error) {
// Backward compatibility for environments not yet migrated to visibilityIndex.
if (!isMissingIndexError(error, 'visibilityIndex')) {
throw error
}
try {
return await queryPublicEntitiesLegacy()
} catch (legacyError) {
// Old local stacks may not have either index yet. Degrade gracefully
// to an empty catalog instead of returning a 500.
Eif (isMissingIndexError(legacyError, 'publicIndex')) {
console.error(
'[catalog/list] visibilityIndex and publicIndex missing - returning empty list'
)
return []
}
throw legacyError
}
}
}
async function getCatalogHandler(event) {
try {
const currentFlowId = event.requestContext?.authorizer?.claims?.['custom:flowId']
if (!currentFlowId) {
return {
statusCode: 401,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({ error: 'Missing flow context' })
}
}
const requestedLimit = parseInt(event.queryStringParameters?.limit || 30, 10)
const limit = Number.isNaN(requestedLimit) ? 30 : Math.min(Math.max(requestedLimit, 1), 100)
const nextToken = event.queryStringParameters?.nextToken
const search = event.queryStringParameters?.search?.toLowerCase()
// Pagination
let offset = 0
if (nextToken) {
const parsedOffset = parseInt(Buffer.from(nextToken, 'base64').toString(), 10)
Eif (Number.isNaN(parsedOffset) || parsedOffset < 0) {
return {
statusCode: 400,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({ error: 'Invalid nextToken' })
}
}
offset = parsedOffset
}
// Query public entities with compatibility fallback for legacy environments.
const publicEntities = await getPublicEntities()
// Filter out entities from the current flow
const otherFlowEntities = publicEntities.filter((e) => e.flowId !== currentFlowId)
// Apply search filter
let filtered = otherFlowEntities
if (search) {
filtered = otherFlowEntities.filter((e) => {
const name = typeof e.name === 'string' ? e.name : e.name?.en || ''
return name.toLowerCase().includes(search)
})
}
// Paginate
const paginatedItems = filtered.slice(offset, offset + limit)
const hasMore = offset + limit < filtered.length
// Fetch flow names for source entities
const uniqueFlowIds = [...new Set(paginatedItems.map((e) => e.flowId))]
const flowsData = {}
for (const flowId of uniqueFlowIds) {
try {
const flowResult = await docClient.send(
new GetCommand({
TableName: FLOWS_TABLE,
Key: { id: flowId }
})
)
Eif (flowResult.Item) {
flowsData[flowId] = flowResult.Item
}
} catch (err) {
console.error(`Error fetching flow ${flowId}:`, err)
}
}
// Fetch forked entities in current flow to mark them
let currentFlowEntities = []
try {
const currentFlowEntitiesResult = await docClient.send(
new QueryCommand({
TableName: ENTITIES_TABLE,
IndexName: 'flowIndex',
KeyConditionExpression: 'flowId = :flowId',
ExpressionAttributeValues: { ':flowId': currentFlowId },
Limit: 1000
})
)
currentFlowEntities = currentFlowEntitiesResult.Items || []
} catch (flowIndexError) {
Iif (!isMissingIndexError(flowIndexError, 'flowIndex')) {
throw flowIndexError
}
// Older local environments might not have flowIndex yet.
console.error('[catalog/list] flowIndex missing - fork status disabled')
}
const forkedEntityIds = new Set(
currentFlowEntities.filter((e) => e.forkedFromEntityId).map((e) => e.forkedFromEntityId)
)
// Fetch linked entities in current flow to mark them
let linkedEntityIds = new Set()
try {
const linksResult = await docClient.send(
new QueryCommand({
TableName: ENTITY_LINKS_TABLE,
KeyConditionExpression: 'flowId = :flowId',
ExpressionAttributeValues: { ':flowId': currentFlowId }
})
)
linkedEntityIds = new Set((linksResult.Items || []).map((l) => l.entityId))
} catch (linkErr) {
console.error('[catalog/list] Error fetching links:', linkErr)
}
// Enrich entities
const enrichedItems = paginatedItems.map((entity) => ({
...entity,
sourceFlowName: flowsData[entity.flowId]?.name || entity.flowId,
forkedByCurrentFlow: forkedEntityIds.has(entity.id),
linkedByCurrentFlow: linkedEntityIds.has(entity.id)
}))
const newNextToken = hasMore ? Buffer.from(String(offset + limit)).toString('base64') : null
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({
items: enrichedItems,
nextToken: newNextToken,
hasMore,
filteredTotal: filtered.length,
total: otherFlowEntities.length
})
}
} catch (error) {
console.error('[catalog/list] Error:', error)
return {
statusCode: 500,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({ error: 'Failed to list catalog' })
}
}
}
module.exports = { getCatalogHandler }
|