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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 22x 22x 22x 96x 24x 16x 16x 8x 4x 6x 4x 4x 4x 8x 22x 20x 20x 20x 20x 20x 22x 21x 21x 21x 16x 10x 21x 21x 4x 4x 2x 2x 19x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 8x 8x 1x 3x 3x 3x 14x 14x 1203x 14x 1203x 1203x 28x 35x 19x 35x 39x 39x 39x 39x 39x 1x 38x 38x 1x 37x 2x 35x 35x 1x 34x 34x 34x 34x 34x 34x 34x 34x 1x 33x 33x 1x 32x 11x 11x 1x 31x 7x 7x 1x 6x 6x 6x 3x 3x 8x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 3x 24x 24x 24x 3x 3x 21x 21x 1x 1x 1x 1x 1x 1x 1x 24x 2x 2x 1x 23x 23x 23x 5x 5x 5x 18x 17x 22x 2x 2x 2x 2x 2x 2x 20x 16x 16x 16x 4x 4x 4x 4x 5x 5x 9x 5x 5x 5x 3x 2x 2x 1x 1x 1x 4x 20x 20x 1x 1x 1x | const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
DynamoDBDocumentClient,
QueryCommand,
GetCommand,
BatchGetCommand
} = require('@aws-sdk/lib-dynamodb')
const {
authenticateRequest,
hasEntityReadPermission,
canAccessEntity
} = require('../shared/auth-helper')
const {
parseFilters,
validateFilterFields,
fetchAllItems,
matchesFilters,
queryLargeEntityFilteredItemIds,
parseSort,
validateSortField,
sortItems,
CREATED_AT_SORT_FIELD_ID
} = require('./filtering')
const { getItemCount } = require('../utils/entityItemCount')
const { getLikeCounts } = require('../utils/itemLikeCount')
const { getLikedItemIds } = require('../utils/itemLikes')
const { getCommentCounts } = require('../utils/commentCount')
const { LARGE_ENTITY_ITEM_THRESHOLD, MAX_FILTER_INDEX_RESULTS } = require('../utils/constants')
const CREATED_AT_INDEX_NAME = 'createdAtIndex'
// The createdAtIndex GSI may not exist yet in an environment that hasn't
// redeployed the CDK stack — mirrors catalog/list.js's isMissingIndexError
// guard for the same situation with visibilityIndex.
function isMissingIndexError(error, indexName) {
return (
error?.name === 'ValidationException' &&
typeof error?.message === 'string' &&
error.message.includes(indexName)
)
}
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
const IGNORED_ITEM_SEARCH_KEYS = new Set([
'id',
'entityId',
'flowId',
'createdAt',
'updatedAt',
'createdBy',
'updatedBy'
])
function getSearchableText(item) {
Iif (!item || typeof item !== 'object') return ''
const parts = []
for (const [key, value] of Object.entries(item)) {
if (IGNORED_ITEM_SEARCH_KEYS.has(key)) continue
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
parts.push(String(value))
continue
}
if (Array.isArray(value)) {
for (const entry of value) {
Eif (entry !== null && entry !== undefined) parts.push(String(entry))
}
continue
}
Eif (value && typeof value === 'object') {
for (const nested of Object.values(value)) {
Eif (nested !== null && nested !== undefined) parts.push(String(nested))
}
}
}
return parts.join(' ').toLowerCase()
}
async function getItemCounts({ entityId, flowId, query }) {
const countQueryParams = {
TableName: process.env.TABLE_NAME,
KeyConditionExpression: 'entityId = :entityId',
FilterExpression: 'flowId = :flowId',
ExpressionAttributeValues: {
':entityId': entityId,
':flowId': flowId
}
}
let total = 0
let filteredTotal = 0
let lastEvaluatedKey
const seenKeys = new Set()
do {
const result = await docClient.send(
new QueryCommand({
...countQueryParams,
ExclusiveStartKey: lastEvaluatedKey
})
)
const pageItems = result.Items || []
total += pageItems.length
if (!query) {
filteredTotal += pageItems.length
} else {
filteredTotal += pageItems.filter((item) => getSearchableText(item).includes(query)).length
}
lastEvaluatedKey = result.LastEvaluatedKey
if (lastEvaluatedKey) {
const keySignature = JSON.stringify(lastEvaluatedKey)
if (seenKeys.has(keySignature)) {
break
}
seenKeys.add(keySignature)
}
} while (lastEvaluatedKey)
return { total, filteredTotal }
}
// Full-scan variant of getItemCounts's loop, for when a `q` search's
// filteredTotal is under the sort threshold: collects every matching item
// (not just one page) so it can be sorted before pagination. Same
// exhaustive-scan cost profile as getItemCounts's existing `query` branch —
// no new cost regime for large entities.
async function fetchAllMatchingByQuery(entityId, flowId, query) {
const queryParams = {
TableName: process.env.TABLE_NAME,
KeyConditionExpression: 'entityId = :entityId',
FilterExpression: 'flowId = :flowId',
ExpressionAttributeValues: { ':entityId': entityId, ':flowId': flowId }
}
const items = []
let lastEvaluatedKey
const seenKeys = new Set()
do {
const result = await docClient.send(
new QueryCommand({ ...queryParams, ExclusiveStartKey: lastEvaluatedKey })
)
const pageItems = result.Items || []
items.push(...pageItems.filter((item) => getSearchableText(item).includes(query)))
lastEvaluatedKey = result.LastEvaluatedKey
Iif (lastEvaluatedKey) {
const keySignature = JSON.stringify(lastEvaluatedKey)
if (seenKeys.has(keySignature)) break
seenKeys.add(keySignature)
}
} while (lastEvaluatedKey)
return items
}
// Structured `filters` pagination uses a plain offset cursor (base64-encoded
// integer) over an already-computed matched-item/id list, rather than a
// DynamoDB LastEvaluatedKey — the matched set isn't a single contiguous
// partition Query result, so there's no native continuation token for it.
function parseOffsetToken(nextToken) {
Eif (!nextToken) return 0
const decoded = parseInt(Buffer.from(nextToken, 'base64').toString(), 10)
return Number.isNaN(decoded) || decoded < 0 ? 0 : decoded
}
function buildOffsetToken(offset, totalLength) {
return offset < totalLength ? Buffer.from(String(offset)).toString('base64') : null
}
// DynamoDB's BatchGetItem caps at 100 keys per call — the page-only caller
// never used to exceed that (page size is clamped to 100), but sorting a
// large-entity filtered result needs every matched item, up to
// LARGE_ENTITY_ITEM_THRESHOLD, hence the chunking.
const BATCH_GET_CHUNK_SIZE = 100
async function batchGetItems(tableName, entityId, itemIds) {
Iif (itemIds.length === 0) return []
const itemsById = new Map()
for (let i = 0; i < itemIds.length; i += BATCH_GET_CHUNK_SIZE) {
const chunk = itemIds.slice(i, i + BATCH_GET_CHUNK_SIZE)
const result = await docClient.send(
new BatchGetCommand({
RequestItems: {
[tableName]: { Keys: chunk.map((id) => ({ entityId, id })) }
}
})
)
for (const item of result.Responses?.[tableName] || []) {
itemsById.set(item.id, item)
}
}
// Preserve the requested (stable-sorted) order rather than whatever order
// BatchGetItem happens to return.
return itemIds.map((id) => itemsById.get(id)).filter(Boolean)
}
// Enriches a page of items with the current user's like state, each item's
// total like count and, for an entity that accepts comments, its comment
// count — reused across list.js's 4 separate return points (small-entity
// filtered, large-entity filtered, in-memory-sorted, and the default
// paginated path) the same way getItemCount already is. The comment counts
// are only read when the entity has comments enabled, so the many entities
// that don't pay nothing for the feature.
async function enrichItemsWithLikes(items, userId, commentsEnabled = false) {
if (items.length === 0) return items
const itemIds = items.map((item) => item.id)
const [likeCounts, likedItemIds, commentCounts] = await Promise.all([
process.env.ITEM_LIKE_COUNT_TABLE_NAME
? getLikeCounts(docClient, process.env.ITEM_LIKE_COUNT_TABLE_NAME, itemIds)
: Promise.resolve(new Map()),
process.env.ITEM_LIKES_TABLE_NAME && userId
? getLikedItemIds(docClient, process.env.ITEM_LIKES_TABLE_NAME, itemIds, userId)
: Promise.resolve(new Set()),
commentsEnabled && process.env.ITEM_COMMENT_COUNT_TABLE_NAME
? getCommentCounts(docClient, process.env.ITEM_COMMENT_COUNT_TABLE_NAME, itemIds)
: Promise.resolve(new Map())
])
return items.map((item) => ({
...item,
likeCount: likeCounts.get(item.id) ?? 0,
likedByCurrentUser: likedItemIds.has(item.id),
...(commentsEnabled && { commentCount: commentCounts.get(item.id) ?? 0 })
}))
}
async function getItemsHandler(event) {
try {
// Authenticate (supports JWT and API keys)
const auth = await authenticateRequest(event)
Iif (!auth || auth.error) {
return {
statusCode: 401,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: auth?.error || 'Authentication required' })
}
}
const entityId = event.pathParameters?.entityId
if (!entityId) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Missing entityId' })
}
}
// Verify entity access — first, get the entity to check access
const entityResult = await docClient.send(
new GetCommand({
TableName: process.env.ENTITIES_TABLE_NAME,
Key: { id: entityId }
})
)
if (!entityResult.Item) {
return {
statusCode: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Entity not found' })
}
}
// Check if auth can access this entity
if (!canAccessEntity(auth, entityResult.Item)) {
return {
statusCode: 403,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Access denied to this entity' })
}
}
// Check permission (collection listing uses the `list` verb, distinct from the
// per-item `read` verb used by GET .../items/{itemId})
const requiredPermission = `entities-${entityId}:items:list`
if (!(await hasEntityReadPermission(auth, entityResult.Item, requiredPermission))) {
return {
statusCode: 403,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: `Permission denied: ${requiredPermission} required` })
}
}
// Get flow from auth context
// For public entities: always use the entity's owner flow to query items
// For owned entities: use the user's current flow
const flowId =
entityResult.Item.visibility === 'public' ? entityResult.Item.flowId : auth.flowId
// Pagination support
const requestedLimit = event.queryStringParameters?.limit
? parseInt(event.queryStringParameters.limit, 10)
: 30
const limit = Number.isNaN(requestedLimit) ? 30 : Math.min(Math.max(requestedLimit, 1), 100)
const nextToken = event.queryStringParameters?.nextToken
const queryRaw = event.queryStringParameters?.q
const query = typeof queryRaw === 'string' ? queryRaw.trim().toLowerCase() : ''
// Structured exact-match field filters — see items/filtering.js.
const filters = parseFilters(event.queryStringParameters?.filters)
if (filters === null) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'INVALID_FILTERS_PARAM' })
}
}
// Optional single-field sort — text-like fields only, and only applied
// when the candidate set it would sort (the whole entity if unfiltered,
// or the matched/filtered count otherwise) is <= LARGE_ENTITY_ITEM_THRESHOLD.
// Above that, `sort` is silently ignored (existing unsorted behavior),
// signaled to the caller via `sorted: false` in the response.
const sort = parseSort(event.queryStringParameters?.sort)
if (sort && sort.error) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'INVALID_SORT_PARAM' })
}
}
if (sort) {
const sortValidation = validateSortField(sort, entityResult.Item.fields || [])
if (!sortValidation.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: sortValidation.code, fieldId: sort.fieldId })
}
}
}
if (filters.length > 0) {
const fieldValidation = validateFilterFields(filters, entityResult.Item.fields || [])
if (!fieldValidation.valid) {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: fieldValidation.code, fieldId: fieldValidation.fieldId })
}
}
const itemCount = process.env.ENTITY_ITEM_COUNT_TABLE_NAME
? await getItemCount(docClient, process.env.ENTITY_ITEM_COUNT_TABLE_NAME, entityId)
: 0
const offset = parseOffsetToken(nextToken)
if (itemCount <= LARGE_ENTITY_ITEM_THRESHOLD) {
const allItems = await fetchAllItems(docClient, process.env.TABLE_NAME, entityId, flowId)
const matched = allItems.filter((item) =>
matchesFilters(item, filters, entityResult.Item.fields || [], entityResult.Item)
)
const canSort = !!sort && matched.length <= LARGE_ENTITY_ITEM_THRESHOLD
if (canSort) sortItems(matched, sort, entityResult.Item.fields || [], entityResult.Item)
const pageItems = matched.slice(offset, offset + limit)
const newOffset = offset + pageItems.length
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
items: await enrichItemsWithLikes(
pageItems,
auth.userId,
entityResult.Item.commentsEnabled === true
),
nextToken: buildOffsetToken(newOffset, matched.length),
hasMore: newOffset < matched.length,
filteredTotal: matched.length,
total: itemCount,
sorted: canSort
})
}
}
const { itemIds, truncated } = await queryLargeEntityFilteredItemIds(
docClient,
process.env.FIELD_VALUE_INDEX_TABLE_NAME,
process.env.TABLE_NAME,
entityId,
filters,
entityResult.Item
)
const sortedIds = [...itemIds].sort()
// createdAt sort reuses the same "materialize everything, sort, offset-
// paginate" mechanism as any other sorted field here, but capped at the
// higher MAX_FILTER_INDEX_RESULTS bound instead of
// LARGE_ENTITY_ITEM_THRESHOLD — that's already the ceiling this path
// imposes on filtered results generally, not a new risk, and creation-
// date sort is meant to always be available regardless of entity size.
const sortCap =
sort?.fieldId === CREATED_AT_SORT_FIELD_ID
? MAX_FILTER_INDEX_RESULTS
: LARGE_ENTITY_ITEM_THRESHOLD
const canSort = !!sort && sortedIds.length <= sortCap
let items
let newOffset
if (canSort) {
const allMatched = await batchGetItems(process.env.TABLE_NAME, entityId, sortedIds)
sortItems(allMatched, sort, entityResult.Item.fields || [], entityResult.Item)
items = allMatched.slice(offset, offset + limit)
newOffset = offset + items.length
} else {
const pageIds = sortedIds.slice(offset, offset + limit)
items = await batchGetItems(process.env.TABLE_NAME, entityId, pageIds)
newOffset = offset + pageIds.length
}
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
items: await enrichItemsWithLikes(
items,
auth.userId,
entityResult.Item.commentsEnabled === true
),
nextToken: buildOffsetToken(newOffset, sortedIds.length),
hasMore: newOffset < sortedIds.length,
filteredTotal: sortedIds.length,
total: itemCount,
sorted: canSort,
...(truncated && { truncated: true })
})
}
}
const queryParams = {
TableName: process.env.TABLE_NAME,
KeyConditionExpression: 'entityId = :entityId',
FilterExpression: 'flowId = :flowId',
ExpressionAttributeValues: {
':entityId': entityId,
':flowId': flowId
},
Limit: limit
}
// createdAt sort is always available (unlike text-field sort, which is
// threshold-gated) — it's backed by a real index, not an in-memory
// fetch-all, so it applies here regardless of entity size: query the
// createdAtIndex GSI directly, newest-first unless direction is 'asc'.
// `sortingByCreatedAt` flips to false if the GSI doesn't exist yet in an
// environment that hasn't redeployed (see queryItemsIndexAware below).
let sortingByCreatedAt = sort?.fieldId === CREATED_AT_SORT_FIELD_ID
if (sortingByCreatedAt) {
queryParams.IndexName = CREATED_AT_INDEX_NAME
queryParams.ScanIndexForward = sort.direction !== 'desc'
}
async function queryItemsIndexAware(params) {
try {
return await docClient.send(new QueryCommand(params))
} catch (err) {
Eif (sortingByCreatedAt && isMissingIndexError(err, CREATED_AT_INDEX_NAME)) {
sortingByCreatedAt = false
delete queryParams.IndexName
delete queryParams.ScanIndexForward
delete params.IndexName
delete params.ScanIndexForward
return docClient.send(new QueryCommand(params))
}
throw err
}
}
// Add pagination token if provided
if (nextToken) {
try {
queryParams.ExclusiveStartKey = JSON.parse(Buffer.from(nextToken, 'base64').toString())
} catch {
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Invalid nextToken' })
}
}
}
let items = []
let lastEvaluatedKey = undefined
// `total` no longer needs its own partition scan when the item-count
// tracker is available — only a `q` substring search still needs a scan,
// to compute filteredTotal (there's no index for "contains").
let total
let filteredTotal
if (query) {
const counts = await getItemCounts({ entityId, flowId, query })
filteredTotal = counts.filteredTotal
total = process.env.ENTITY_ITEM_COUNT_TABLE_NAME
? await getItemCount(docClient, process.env.ENTITY_ITEM_COUNT_TABLE_NAME, entityId)
: counts.total
} else {
total = process.env.ENTITY_ITEM_COUNT_TABLE_NAME
? await getItemCount(docClient, process.env.ENTITY_ITEM_COUNT_TABLE_NAME, entityId)
: (await getItemCounts({ entityId, flowId, query: '' })).total
filteredTotal = total
}
// Same in-memory-fetch-then-sort approach as the structured-filters small-
// entity path above, applied here (unfiltered listing, or a `q` search)
// when the candidate set is small enough — offset-token paginated like
// that path too, instead of the native DynamoDB Query/ExclusiveStartKey
// pagination used below when sort isn't requested or doesn't apply.
if (
sort &&
sort.fieldId !== CREATED_AT_SORT_FIELD_ID &&
filteredTotal <= LARGE_ENTITY_ITEM_THRESHOLD
) {
const offset = parseOffsetToken(nextToken)
const allMatching = query
? await fetchAllMatchingByQuery(entityId, flowId, query)
: await fetchAllItems(docClient, process.env.TABLE_NAME, entityId, flowId)
sortItems(allMatching, sort, entityResult.Item.fields || [], entityResult.Item)
const pageItems = allMatching.slice(offset, offset + limit)
const newOffset = offset + pageItems.length
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
items: await enrichItemsWithLikes(
pageItems,
auth.userId,
entityResult.Item.commentsEnabled === true
),
nextToken: buildOffsetToken(newOffset, allMatching.length),
hasMore: newOffset < allMatching.length,
filteredTotal: allMatching.length,
total,
sorted: true
})
}
}
if (!query) {
const result = await queryItemsIndexAware(queryParams)
items = result.Items || []
lastEvaluatedKey = result.LastEvaluatedKey
} else {
// Query items by entityId (partition key) and filter by flowId.
// When query filtering is requested, iterate pages until enough matches are collected.
const aggregatedItems = []
let currentQueryParams = { ...queryParams }
const seenKeys = new Set()
while (aggregatedItems.length < limit) {
const result = await queryItemsIndexAware(currentQueryParams)
const pageItems = result.Items || []
const matchingItems = pageItems.filter((item) => getSearchableText(item).includes(query))
aggregatedItems.push(...matchingItems)
lastEvaluatedKey = result.LastEvaluatedKey
if (!lastEvaluatedKey) {
break
}
const keySignature = JSON.stringify(lastEvaluatedKey)
if (seenKeys.has(keySignature)) {
break
}
seenKeys.add(keySignature)
currentQueryParams = {
...queryParams,
ExclusiveStartKey: lastEvaluatedKey
}
}
items = aggregatedItems.slice(0, limit)
}
// Encode LastEvaluatedKey for next request
const responseNextToken = lastEvaluatedKey
? Buffer.from(JSON.stringify(lastEvaluatedKey)).toString('base64')
: null
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
items: await enrichItemsWithLikes(
items,
auth.userId,
entityResult.Item.commentsEnabled === true
),
nextToken: responseNextToken,
hasMore: !!lastEvaluatedKey,
filteredTotal,
total,
sorted: sortingByCreatedAt
})
}
} catch (error) {
console.error('Error fetching items:', error)
return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({ error: 'Failed to fetch items' })
}
}
}
exports.handler = getItemsHandler
|