All files / entities import-check.js

88.88% Statements 48/54
81.81% Branches 18/22
100% Functions 3/3
94.11% Lines 48/51

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 1351x 1x 1x 1x 1x 1x           1x   1x 1x     7x                     7x 7x 7x   7x 7x   1x                       7x 7x 7x 1x     6x 6x       6x 6x 1x     5x   5x 5x 6x   6x 6x 1x 1x     5x 5x 1x 1x     4x 2x                   2x     2x           2x 1x       1x                           1x     1x     5x             1x  
const { getActiveFlowId } = require('../shared/activeFlow')
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
const { requirePermission } = require('../utils/requirePermission')
const { findEntityNameConflict } = require('../utils/nameUniqueness')
const { computeFieldCompatibility } = require('../utils/entityFieldCompatibility')
const {
  validateEntitySchema,
  checkReservedName,
  findBatchNameConflicts,
  getDisplayName
} = require('../utils/importValidation')
 
const client = new DynamoDBClient({})
const docClient = DynamoDBDocumentClient.from(client)
 
function jsonResponse(statusCode, body) {
  return {
    statusCode,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    },
    body: JSON.stringify(body)
  }
}
 
function safeParseBody(rawBody) {
  Iif (!rawBody) return {}
  Iif (typeof rawBody === 'object') return rawBody
  Iif (typeof rawBody !== 'string') return {}
 
  try {
    return JSON.parse(rawBody)
  } catch {
    return null
  }
}
 
/**
 * Dry-run validation for a bundle about to be imported — writes nothing.
 * Populates the Import Preview screen with, per entity: whether its schema
 * is valid, and whether its name conflicts with an existing entity in the
 * active flow (and if so, whether merging is offered) or with another
 * entity in the same bundle (never mergeable — only renaming resolves it).
 */
async function importCheckHandler(event) {
  try {
    const body = safeParseBody(event.body)
    if (body === null) {
      return jsonResponse(400, { error: 'Invalid JSON body' })
    }
 
    const flowId = await getActiveFlowId(event)
    Iif (!flowId) {
      return jsonResponse(401, { error: 'Missing flow context' })
    }
 
    const entries = Array.isArray(body.entities) ? body.entities : []
    if (entries.length === 0) {
      return jsonResponse(400, { error: 'Missing entities' })
    }
 
    const batchConflictTempIds = findBatchNameConflicts(entries)
 
    const results = []
    for (const entry of entries) {
      const { tempId, entity } = entry
 
      const schemaValidation = validateEntitySchema(entity)
      if (!schemaValidation.valid) {
        results.push({ tempId, valid: false, error: schemaValidation.error })
        continue
      }
 
      const reservedCheck = checkReservedName(entity.name)
      if (!reservedCheck.valid) {
        results.push({ tempId, valid: false, error: reservedCheck.error })
        continue
      }
 
      if (batchConflictTempIds.has(tempId)) {
        results.push({
          tempId,
          valid: true,
          nameConflict: {
            source: 'batch',
            compatible: false,
            conflictingEntityName: getDisplayName(entity.name, 'Untitled'),
            missingFields: []
          }
        })
        continue
      }
 
      const existingConflict = await findEntityNameConflict(docClient, {
        tableName: process.env.TABLE_NAME,
        flowId,
        name: entity.name
      })
 
      if (existingConflict) {
        const { compatible, missingFields } = computeFieldCompatibility(
          entity.fields,
          existingConflict.fields
        )
        results.push({
          tempId,
          valid: true,
          nameConflict: {
            source: 'existing',
            conflictingEntityId: existingConflict.id,
            conflictingEntityName: getDisplayName(
              existingConflict.name,
              getDisplayName(entity.name, 'Untitled')
            ),
            compatible,
            missingFields
          }
        })
        continue
      }
 
      results.push({ tempId, valid: true, nameConflict: null })
    }
 
    return jsonResponse(200, { results })
  } catch (error) {
    console.error('[import-check] Exception:', error.message, error.stack)
    return jsonResponse(500, { error: 'Failed to check import' })
  }
}
 
exports.handler = requirePermission(importCheckHandler, { permission: 'entities:create' })