All files / items list.js

97.97% Statements 97/99
84% Branches 63/75
100% Functions 5/5
98.92% Lines 92/93

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 2871x 1x 1x   1x 1x   1x                     10x 10x 10x 42x 12x 4x 4x   8x 4x 6x   4x   4x 4x 8x       10x       13x                   13x 13x   13x   13x 15x             14x 14x   14x 11x   4x     14x 14x 4x 4x 2x   2x       12x       18x   18x   18x 1x                     17x                     17x   17x 1x                       16x             16x 1x                     15x 1x                           14x             14x     14x 14x 14x 14x   14x                       14x 2x 2x   1x                     13x 13x   13x           12x 9x 9x 9x       3x 3x 3x   3x 4x 4x 6x   4x 4x   4x 2x     2x 2x 1x   1x   1x           3x       12x       12x                             1x 1x                     1x  
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, QueryCommand, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { authenticateRequest, hasPermission, canAccessEntity } = require('../shared/auth-helper')
 
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 }
}
 
async function getItemsHandler(event) {
  try {
    // Authenticate (supports JWT and API keys)
    const auth = await authenticateRequest(event)
 
    if (!auth || auth.error) {
      return {
        statusCode: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: auth?.error || 'Authentication required' })
      }
    }
 
    // Check permission
    Iif (!hasPermission(auth, 'items:read')) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Permission denied: items:read 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 (important for API keys with allowedEntityIds)
    // 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' })
      }
    }
 
    // 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.type === 'apikey' && (auth.allowedEntityIds || []).includes('*')
          ? 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() : ''
 
    const queryParams = {
      TableName: process.env.TABLE_NAME,
      KeyConditionExpression: 'entityId = :entityId',
      FilterExpression: 'flowId = :flowId',
      ExpressionAttributeValues: {
        ':entityId': entityId,
        ':flowId': flowId
      },
      Limit: limit
    }
 
    // 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
 
    const { total, filteredTotal } = await getItemCounts({
      entityId,
      flowId,
      query
    })
 
    if (!query) {
      const result = await docClient.send(new QueryCommand(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 docClient.send(new QueryCommand(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,
        nextToken: responseNextToken,
        hasMore: !!lastEvaluatedKey,
        filteredTotal,
        total
      })
    }
  } 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