All files / entities export.js

87.23% Statements 41/47
77.41% Branches 24/31
100% Functions 4/4
93.18% Lines 41/44

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 1201x 1x 1x 1x 1x 1x   1x     7x                     7x 7x 7x   7x 7x   1x                       7x 7x 7x 1x     6x 6x   6x       6x 6x 1x     5x   5x 5x   2x   5x       5x       5x         5x 6x 6x 2x   4x 1x       2x                               2x             2x             1x  
const { getActiveFlowId } = require('../shared/activeFlow')
const { SQSClient, SendMessageCommand } = require('@aws-sdk/client-sqs')
const { requirePermission } = require('../utils/requirePermission')
const { permissionChecker } = require('../utils/PermissionChecker')
const { fetchEntity, isAccessible } = require('../utils/entityBundleDiscovery')
const { createJob } = require('../utils/jobsTable')
 
const sqsClient = new SQSClient({})
 
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
  }
}
 
/**
 * Submit handler — validates the request and each requested (root) entity's
 * accessibility (fast, so the caller gets an immediate 404/403 instead of
 * finding out only after polling), then hands the actual discovery/zip-build
 * work to export-worker.js via SQS. Runs async because a large, multi-image
 * bundle can take far longer than API Gateway's 29s hard integration timeout.
 */
async function exportEntitiesHandler(event) {
  try {
    const body = safeParseBody(event.body)
    if (body === null) {
      return jsonResponse(400, { error: 'Invalid JSON body' })
    }
 
    const flowId = await getActiveFlowId(event)
    const userId = event.requestContext?.authorizer?.claims?.sub
 
    Iif (!flowId) {
      return jsonResponse(401, { error: 'Missing flow context' })
    }
 
    const entityIds = Array.isArray(body.entityIds) ? body.entityIds : []
    if (entityIds.length === 0) {
      return jsonResponse(400, { error: 'Missing entityIds' })
    }
 
    const format = body.format === 'csv' ? 'csv' : 'json'
 
    const rootIds = new Set(entityIds)
    const excludeEntityIds = (
      Array.isArray(body.excludeEntityIds) ? body.excludeEntityIds : []
    ).filter((id) => !rootIds.has(id))
    const excludeItemsEntityIds =
      format === 'json' && Array.isArray(body.excludeItemsEntityIds)
        ? body.excludeItemsEntityIds
        : []
    const excludeImagesEntityIds =
      format === 'json' && Array.isArray(body.excludeImagesEntityIds)
        ? body.excludeImagesEntityIds
        : []
 
    const { permissions: callerPermissions = [] } = await permissionChecker.getUserPermissions(
      userId,
      flowId
    )
 
    for (const id of entityIds) {
      const entity = await fetchEntity(id)
      if (!entity) {
        return jsonResponse(404, { error: `Entity not found: ${id}` })
      }
      if (!isAccessible(entity, flowId, callerPermissions)) {
        return jsonResponse(403, { error: `Access denied to entity: ${id}` })
      }
    }
 
    const job = await createJob({
      type: 'export',
      flowId,
      userId,
      request: {
        entityIds,
        format,
        excludeEntityIds,
        excludeItemsEntityIds,
        excludeImagesEntityIds
      },
      // Discovery hasn't run yet — the worker fills this in once it knows how
      // many entities/images the bundle actually contains.
      total: null
    })
 
    await sqsClient.send(
      new SendMessageCommand({
        QueueUrl: process.env.EXPORT_JOBS_QUEUE_URL,
        MessageBody: JSON.stringify({ jobId: job.id })
      })
    )
 
    return jsonResponse(202, { jobId: job.id })
  } catch (error) {
    console.error('[export] Exception:', error.message, error.stack)
    return jsonResponse(500, { error: 'Failed to export entities' })
  }
}
 
exports.handler = requirePermission(exportEntitiesHandler, { permission: 'entities:list' })