All files / items create.js

96.66% Statements 58/60
84.37% Branches 54/64
100% Functions 3/3
98.21% Lines 55/56

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 2351x           1x 1x 1x 1x   1x 1x       3x 2x 2x   1x     1x 28x   28x 28x 1x                   27x                     27x   26x 1x                     25x   25x 1x                     24x             23x 1x                   22x     22x 1x                       21x       21x     21x 33x 3x 2x                         19x 31x 2x 2x 2x                 2x 1x                       18x 30x                 30x 1x                                   17x 29x 2x       17x                   17x             17x                 2x 2x                     1x  
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const {
  DynamoDBDocumentClient,
  PutCommand,
  GetCommand,
  QueryCommand
} = require('@aws-sdk/lib-dynamodb')
const { randomUUID } = require('crypto')
const { authenticateRequest, hasPermission, canAccessEntity } = require('../shared/auth-helper')
const { validateFieldReference } = require('./reference-validation')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
// Returns true when a field value should be treated as "not provided"
function isEmptyValue(value) {
  if (value === undefined || value === null || value === '') return true
  if (typeof value === 'object' && !Array.isArray(value)) {
    return Object.keys(value).length === 0 || Object.values(value).every((v) => !v || v === '')
  }
  return false
}
 
const createItemHandler = async (event) => {
  try {
    // Authenticate — supports Cognito JWT (gateway or header) 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' })
      }
    }
 
    Iif (!hasPermission(auth, 'items:write')) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Permission denied: items:write required' })
      }
    }
 
    const body = JSON.parse(event.body || '{}')
 
    if (!body.data) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing required fields: entityId, data' })
      }
    }
 
    // entityId comes from path parameter; body.entityId kept for backward compatibility
    const entityId = event.pathParameters?.entityId || body.entityId
 
    if (!entityId) {
      return {
        statusCode: 400,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Missing entityId' })
      }
    }
 
    // Verify entity exists and caller has 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' })
      }
    }
 
    const entity = entityResult.Item
 
    // canAccessEntity handles: public entities, flow ownership, API key allowedEntityIds
    if (!canAccessEntity(auth, entity)) {
      return {
        statusCode: 403,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({ error: 'Access denied to this entity' })
      }
    }
 
    // For API key with wildcard access, items belong to the entity's owner flow
    const flowId =
      auth.type === 'apikey' && (auth.allowedEntityIds || []).includes('*')
        ? entity.flowId
        : auth.flowId
 
    const fields = entity.fields || []
 
    // Validate mandatory fields (boolean/workflow types are never required)
    for (const field of fields) {
      if (field.mandatory && !['boolean', 'workflow'].includes(field.type)) {
        if (isEmptyValue(body.data[field.fieldId])) {
          return {
            statusCode: 400,
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin': '*'
            },
            body: JSON.stringify({ error: 'MANDATORY_FIELD_MISSING', fieldId: field.fieldId })
          }
        }
      }
    }
 
    // Check uniqueness for fields with unique: true
    for (const field of fields) {
      if (!field.unique) continue
      const value = body.data[field.fieldId]
      Iif (value === undefined || value === null || value === '') continue
      const existing = await docClient.send(
        new QueryCommand({
          TableName: process.env.TABLE_NAME,
          KeyConditionExpression: 'entityId = :eid',
          FilterExpression: '#fieldId = :fieldValue',
          ExpressionAttributeNames: { '#fieldId': field.fieldId },
          ExpressionAttributeValues: { ':eid': entityId, ':fieldValue': value }
        })
      )
      if (existing.Items && existing.Items.length > 0) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({ error: 'UNIQUE_FIELD_CONFLICT', fieldId: field.fieldId })
        }
      }
    }
 
    // Validate foreign-key style references against their target scope.
    for (const field of fields) {
      const referenceCheck = await validateFieldReference({
        docClient,
        field,
        value: body.data[field.fieldId],
        flowId,
        flowMembershipsTableName: process.env.FLOW_MEMBERSHIPS_TABLE_NAME,
        itemsTableName: process.env.TABLE_NAME
      })
 
      if (!referenceCheck.valid) {
        return {
          statusCode: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
          },
          body: JSON.stringify({
            error: referenceCheck.error,
            fieldId: referenceCheck.fieldId,
            referenceType: referenceCheck.referenceType
          })
        }
      }
    }
 
    // Auto-assign startStateId for workflow fields — always enforced server-side.
    // The create form never shows workflow fields, so no client value should be
    // trusted here even if one was sent.
    for (const field of fields) {
      if (field.type === 'workflow' && field.workflowDefinition?.startStateId) {
        body.data[field.fieldId] = field.workflowDefinition.startStateId
      }
    }
 
    const item = {
      entityId: entity.id,
      id: randomUUID(),
      flowId,
      createdBy: auth.userId,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      ...body.data
    }
 
    await docClient.send(
      new PutCommand({
        TableName: process.env.TABLE_NAME,
        Item: item
      })
    )
 
    return {
      statusCode: 201,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify(item)
    }
  } catch (error) {
    console.error('Error:', error)
    return {
      statusCode: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({ error: 'Failed to create item' })
    }
  }
}
 
exports.handler = createItemHandler