|
| 1 | +import { randomUUID } from 'crypto' |
| 2 | +import { createLogger } from '@sim/logger' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { z } from 'zod' |
| 5 | +import { createRawDynamoDBClient, describeTable, listTables } from '@/app/api/tools/dynamodb/utils' |
| 6 | + |
| 7 | +const logger = createLogger('DynamoDBIntrospectAPI') |
| 8 | + |
| 9 | +const IntrospectSchema = z.object({ |
| 10 | + region: z.string().min(1, 'AWS region is required'), |
| 11 | + accessKeyId: z.string().min(1, 'AWS access key ID is required'), |
| 12 | + secretAccessKey: z.string().min(1, 'AWS secret access key is required'), |
| 13 | + tableName: z.string().optional(), |
| 14 | +}) |
| 15 | + |
| 16 | +export async function POST(request: NextRequest) { |
| 17 | + const requestId = randomUUID().slice(0, 8) |
| 18 | + |
| 19 | + try { |
| 20 | + const body = await request.json() |
| 21 | + const params = IntrospectSchema.parse(body) |
| 22 | + |
| 23 | + logger.info(`[${requestId}] Introspecting DynamoDB in region ${params.region}`) |
| 24 | + |
| 25 | + const client = createRawDynamoDBClient({ |
| 26 | + region: params.region, |
| 27 | + accessKeyId: params.accessKeyId, |
| 28 | + secretAccessKey: params.secretAccessKey, |
| 29 | + }) |
| 30 | + |
| 31 | + try { |
| 32 | + const { tables } = await listTables(client) |
| 33 | + |
| 34 | + if (params.tableName) { |
| 35 | + logger.info(`[${requestId}] Describing table: ${params.tableName}`) |
| 36 | + const { tableDetails } = await describeTable(client, params.tableName) |
| 37 | + |
| 38 | + logger.info(`[${requestId}] Table description completed for '${params.tableName}'`) |
| 39 | + |
| 40 | + return NextResponse.json({ |
| 41 | + message: `Table '${params.tableName}' described successfully.`, |
| 42 | + tables, |
| 43 | + tableDetails, |
| 44 | + }) |
| 45 | + } |
| 46 | + |
| 47 | + logger.info(`[${requestId}] Listed ${tables.length} tables`) |
| 48 | + |
| 49 | + return NextResponse.json({ |
| 50 | + message: `Found ${tables.length} table(s) in region '${params.region}'.`, |
| 51 | + tables, |
| 52 | + }) |
| 53 | + } finally { |
| 54 | + client.destroy() |
| 55 | + } |
| 56 | + } catch (error) { |
| 57 | + if (error instanceof z.ZodError) { |
| 58 | + logger.warn(`[${requestId}] Invalid request data`, { errors: error.errors }) |
| 59 | + return NextResponse.json( |
| 60 | + { error: 'Invalid request data', details: error.errors }, |
| 61 | + { status: 400 } |
| 62 | + ) |
| 63 | + } |
| 64 | + |
| 65 | + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred' |
| 66 | + logger.error(`[${requestId}] DynamoDB introspection failed:`, error) |
| 67 | + |
| 68 | + return NextResponse.json( |
| 69 | + { error: `DynamoDB introspection failed: ${errorMessage}` }, |
| 70 | + { status: 500 } |
| 71 | + ) |
| 72 | + } |
| 73 | +} |
0 commit comments