chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { awsDynamodbDeleteContract } from '@/lib/api/contracts/tools/aws/dynamodb-delete'
|
||||
import { parseToolRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createDynamoDBClient, deleteItem } from '@/app/api/tools/dynamodb/utils'
|
||||
|
||||
const logger = createLogger('DynamoDBDeleteAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseToolRequest(awsDynamodbDeleteContract, request, {
|
||||
errorFormat: 'details',
|
||||
logger,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
logger.info(`Deleting item from table '${validatedData.tableName}'`)
|
||||
|
||||
const client = createDynamoDBClient({
|
||||
region: validatedData.region,
|
||||
accessKeyId: validatedData.accessKeyId,
|
||||
secretAccessKey: validatedData.secretAccessKey,
|
||||
})
|
||||
|
||||
try {
|
||||
await deleteItem(client, validatedData.tableName, validatedData.key, {
|
||||
conditionExpression: validatedData.conditionExpression,
|
||||
expressionAttributeNames: validatedData.expressionAttributeNames,
|
||||
expressionAttributeValues: validatedData.expressionAttributeValues,
|
||||
})
|
||||
|
||||
logger.info(`Delete completed for table '${validatedData.tableName}'`)
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Item deleted successfully',
|
||||
})
|
||||
} finally {
|
||||
client.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = toError(error).message || 'DynamoDB delete failed'
|
||||
logger.error('DynamoDB delete failed:', error)
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { awsDynamodbGetContract } from '@/lib/api/contracts/tools/aws/dynamodb-get'
|
||||
import { parseToolRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createDynamoDBClient, getItem } from '@/app/api/tools/dynamodb/utils'
|
||||
|
||||
const logger = createLogger('DynamoDBGetAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseToolRequest(awsDynamodbGetContract, request, {
|
||||
errorFormat: 'details',
|
||||
logger,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
logger.info(`Getting item from table '${validatedData.tableName}'`)
|
||||
|
||||
const client = createDynamoDBClient({
|
||||
region: validatedData.region,
|
||||
accessKeyId: validatedData.accessKeyId,
|
||||
secretAccessKey: validatedData.secretAccessKey,
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await getItem(
|
||||
client,
|
||||
validatedData.tableName,
|
||||
validatedData.key,
|
||||
validatedData.consistentRead
|
||||
)
|
||||
|
||||
logger.info(`Get item completed for table '${validatedData.tableName}'`)
|
||||
|
||||
return NextResponse.json({
|
||||
message: result.item ? 'Item retrieved successfully' : 'Item not found',
|
||||
item: result.item,
|
||||
})
|
||||
} finally {
|
||||
client.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = toError(error).message || 'DynamoDB get failed'
|
||||
logger.error('DynamoDB get failed:', error)
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { awsDynamodbIntrospectContract } from '@/lib/api/contracts/tools/aws/dynamodb-introspect'
|
||||
import { parseToolRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createRawDynamoDBClient, describeTable, listTables } from '@/app/api/tools/dynamodb/utils'
|
||||
|
||||
const logger = createLogger('DynamoDBIntrospectAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseToolRequest(awsDynamodbIntrospectContract, request, {
|
||||
errorFormat: 'details',
|
||||
logger,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
const params = parsed.data.body
|
||||
|
||||
logger.info(`Introspecting DynamoDB in region ${params.region}`)
|
||||
|
||||
const client = createRawDynamoDBClient({
|
||||
region: params.region,
|
||||
accessKeyId: params.accessKeyId,
|
||||
secretAccessKey: params.secretAccessKey,
|
||||
})
|
||||
|
||||
try {
|
||||
const { tables } = await listTables(client)
|
||||
|
||||
if (params.tableName) {
|
||||
logger.info(`Describing table: ${params.tableName}`)
|
||||
const { tableDetails } = await describeTable(client, params.tableName)
|
||||
|
||||
logger.info(`Table description completed for '${params.tableName}'`)
|
||||
|
||||
return NextResponse.json({
|
||||
message: `Table '${params.tableName}' described successfully.`,
|
||||
tables,
|
||||
tableDetails,
|
||||
})
|
||||
}
|
||||
|
||||
logger.info(`Listed ${tables.length} tables`)
|
||||
|
||||
return NextResponse.json({
|
||||
message: `Found ${tables.length} table(s) in region '${params.region}'.`,
|
||||
tables,
|
||||
})
|
||||
} finally {
|
||||
client.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = toError(error).message || 'Unknown error occurred'
|
||||
logger.error('DynamoDB introspection failed:', error)
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: `DynamoDB introspection failed: ${errorMessage}` },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { awsDynamodbPutContract } from '@/lib/api/contracts/tools/aws/dynamodb-put'
|
||||
import { parseToolRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createDynamoDBClient, putItem } from '@/app/api/tools/dynamodb/utils'
|
||||
|
||||
const logger = createLogger('DynamoDBPutAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseToolRequest(awsDynamodbPutContract, request, {
|
||||
errorFormat: 'details',
|
||||
logger,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
logger.info(`Putting item into table '${validatedData.tableName}'`)
|
||||
|
||||
const client = createDynamoDBClient({
|
||||
region: validatedData.region,
|
||||
accessKeyId: validatedData.accessKeyId,
|
||||
secretAccessKey: validatedData.secretAccessKey,
|
||||
})
|
||||
|
||||
try {
|
||||
await putItem(client, validatedData.tableName, validatedData.item, {
|
||||
conditionExpression: validatedData.conditionExpression,
|
||||
expressionAttributeNames: validatedData.expressionAttributeNames,
|
||||
expressionAttributeValues: validatedData.expressionAttributeValues,
|
||||
})
|
||||
|
||||
logger.info(`Put item completed for table '${validatedData.tableName}'`)
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Item created successfully',
|
||||
item: validatedData.item,
|
||||
})
|
||||
} finally {
|
||||
client.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = toError(error).message || 'DynamoDB put failed'
|
||||
logger.error('DynamoDB put failed:', error)
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { awsDynamodbQueryContract } from '@/lib/api/contracts/tools/aws/dynamodb-query'
|
||||
import { parseToolRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createDynamoDBClient, queryItems } from '@/app/api/tools/dynamodb/utils'
|
||||
|
||||
const logger = createLogger('DynamoDBQueryAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseToolRequest(awsDynamodbQueryContract, request, {
|
||||
errorFormat: 'details',
|
||||
logger,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
logger.info(`Querying table '${validatedData.tableName}'`)
|
||||
|
||||
const client = createDynamoDBClient({
|
||||
region: validatedData.region,
|
||||
accessKeyId: validatedData.accessKeyId,
|
||||
secretAccessKey: validatedData.secretAccessKey,
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await queryItems(
|
||||
client,
|
||||
validatedData.tableName,
|
||||
validatedData.keyConditionExpression,
|
||||
{
|
||||
filterExpression: validatedData.filterExpression,
|
||||
expressionAttributeNames: validatedData.expressionAttributeNames,
|
||||
expressionAttributeValues: validatedData.expressionAttributeValues,
|
||||
indexName: validatedData.indexName,
|
||||
limit: validatedData.limit,
|
||||
exclusiveStartKey: validatedData.exclusiveStartKey,
|
||||
scanIndexForward: validatedData.scanIndexForward,
|
||||
}
|
||||
)
|
||||
|
||||
logger.info(
|
||||
`Query completed for table '${validatedData.tableName}', returned ${result.count} items`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
message: `Query returned ${result.count} items`,
|
||||
items: result.items,
|
||||
count: result.count,
|
||||
...(result.lastEvaluatedKey && { lastEvaluatedKey: result.lastEvaluatedKey }),
|
||||
})
|
||||
} finally {
|
||||
client.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = toError(error).message || 'DynamoDB query failed'
|
||||
logger.error('DynamoDB query failed:', error)
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { awsDynamodbScanContract } from '@/lib/api/contracts/tools/aws/dynamodb-scan'
|
||||
import { parseToolRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createDynamoDBClient, scanItems } from '@/app/api/tools/dynamodb/utils'
|
||||
|
||||
const logger = createLogger('DynamoDBScanAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseToolRequest(awsDynamodbScanContract, request, {
|
||||
errorFormat: 'details',
|
||||
logger,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
logger.info(`Scanning table '${validatedData.tableName}'`)
|
||||
|
||||
const client = createDynamoDBClient({
|
||||
region: validatedData.region,
|
||||
accessKeyId: validatedData.accessKeyId,
|
||||
secretAccessKey: validatedData.secretAccessKey,
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await scanItems(client, validatedData.tableName, {
|
||||
filterExpression: validatedData.filterExpression,
|
||||
projectionExpression: validatedData.projectionExpression,
|
||||
expressionAttributeNames: validatedData.expressionAttributeNames,
|
||||
expressionAttributeValues: validatedData.expressionAttributeValues,
|
||||
limit: validatedData.limit,
|
||||
exclusiveStartKey: validatedData.exclusiveStartKey,
|
||||
})
|
||||
|
||||
logger.info(
|
||||
`Scan completed for table '${validatedData.tableName}', returned ${result.count} items`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
message: `Scan returned ${result.count} items`,
|
||||
items: result.items,
|
||||
count: result.count,
|
||||
...(result.lastEvaluatedKey && { lastEvaluatedKey: result.lastEvaluatedKey }),
|
||||
})
|
||||
} finally {
|
||||
client.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = toError(error).message || 'DynamoDB scan failed'
|
||||
logger.error('DynamoDB scan failed:', error)
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { toError } from '@sim/utils/errors'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { awsDynamodbUpdateContract } from '@/lib/api/contracts/tools/aws/dynamodb-update'
|
||||
import { parseToolRequest } from '@/lib/api/server'
|
||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { createDynamoDBClient, updateItem } from '@/app/api/tools/dynamodb/utils'
|
||||
|
||||
const logger = createLogger('DynamoDBUpdateAPI')
|
||||
|
||||
export const POST = withRouteHandler(async (request: NextRequest) => {
|
||||
try {
|
||||
const auth = await checkInternalAuth(request)
|
||||
if (!auth.success || !auth.userId) {
|
||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseToolRequest(awsDynamodbUpdateContract, request, {
|
||||
errorFormat: 'details',
|
||||
logger,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
const validatedData = parsed.data.body
|
||||
|
||||
logger.info(`Updating item in table '${validatedData.tableName}'`)
|
||||
|
||||
const client = createDynamoDBClient({
|
||||
region: validatedData.region,
|
||||
accessKeyId: validatedData.accessKeyId,
|
||||
secretAccessKey: validatedData.secretAccessKey,
|
||||
})
|
||||
|
||||
try {
|
||||
const result = await updateItem(
|
||||
client,
|
||||
validatedData.tableName,
|
||||
validatedData.key,
|
||||
validatedData.updateExpression,
|
||||
{
|
||||
expressionAttributeNames: validatedData.expressionAttributeNames,
|
||||
expressionAttributeValues: validatedData.expressionAttributeValues,
|
||||
conditionExpression: validatedData.conditionExpression,
|
||||
}
|
||||
)
|
||||
|
||||
logger.info(`Update completed for table '${validatedData.tableName}'`)
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Item updated successfully',
|
||||
item: result.attributes,
|
||||
})
|
||||
} finally {
|
||||
client.destroy()
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = toError(error).message || 'DynamoDB update failed'
|
||||
logger.error('DynamoDB update failed:', error)
|
||||
return NextResponse.json({ error: errorMessage }, { status: 500 })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,308 @@
|
||||
import { DescribeTableCommand, DynamoDBClient, ListTablesCommand } from '@aws-sdk/client-dynamodb'
|
||||
import {
|
||||
DeleteCommand,
|
||||
DynamoDBDocumentClient,
|
||||
GetCommand,
|
||||
PutCommand,
|
||||
QueryCommand,
|
||||
ScanCommand,
|
||||
UpdateCommand,
|
||||
} from '@aws-sdk/lib-dynamodb'
|
||||
import type { DynamoDBConnectionConfig, DynamoDBTableSchema } from '@/tools/dynamodb/types'
|
||||
|
||||
export function createDynamoDBClient(config: DynamoDBConnectionConfig): DynamoDBDocumentClient {
|
||||
const client = new DynamoDBClient({
|
||||
region: config.region,
|
||||
credentials: {
|
||||
accessKeyId: config.accessKeyId,
|
||||
secretAccessKey: config.secretAccessKey,
|
||||
},
|
||||
})
|
||||
|
||||
return DynamoDBDocumentClient.from(client, {
|
||||
marshallOptions: {
|
||||
removeUndefinedValues: true,
|
||||
convertEmptyValues: false,
|
||||
},
|
||||
unmarshallOptions: {
|
||||
wrapNumbers: false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getItem(
|
||||
client: DynamoDBDocumentClient,
|
||||
tableName: string,
|
||||
key: Record<string, unknown>,
|
||||
consistentRead?: boolean
|
||||
): Promise<{ item: Record<string, unknown> | null }> {
|
||||
const command = new GetCommand({
|
||||
TableName: tableName,
|
||||
Key: key,
|
||||
ConsistentRead: consistentRead,
|
||||
})
|
||||
|
||||
const response = await client.send(command)
|
||||
return {
|
||||
item: (response.Item as Record<string, unknown>) || null,
|
||||
}
|
||||
}
|
||||
|
||||
export async function putItem(
|
||||
client: DynamoDBDocumentClient,
|
||||
tableName: string,
|
||||
item: Record<string, unknown>,
|
||||
options?: {
|
||||
conditionExpression?: string
|
||||
expressionAttributeNames?: Record<string, string>
|
||||
expressionAttributeValues?: Record<string, unknown>
|
||||
}
|
||||
): Promise<{ success: boolean }> {
|
||||
const command = new PutCommand({
|
||||
TableName: tableName,
|
||||
Item: item,
|
||||
...(options?.conditionExpression && { ConditionExpression: options.conditionExpression }),
|
||||
...(options?.expressionAttributeNames && {
|
||||
ExpressionAttributeNames: options.expressionAttributeNames,
|
||||
}),
|
||||
...(options?.expressionAttributeValues && {
|
||||
ExpressionAttributeValues: options.expressionAttributeValues,
|
||||
}),
|
||||
})
|
||||
|
||||
await client.send(command)
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
export async function queryItems(
|
||||
client: DynamoDBDocumentClient,
|
||||
tableName: string,
|
||||
keyConditionExpression: string,
|
||||
options?: {
|
||||
filterExpression?: string
|
||||
expressionAttributeNames?: Record<string, string>
|
||||
expressionAttributeValues?: Record<string, unknown>
|
||||
indexName?: string
|
||||
limit?: number
|
||||
exclusiveStartKey?: Record<string, unknown>
|
||||
scanIndexForward?: boolean
|
||||
}
|
||||
): Promise<{
|
||||
items: Record<string, unknown>[]
|
||||
count: number
|
||||
lastEvaluatedKey?: Record<string, unknown>
|
||||
}> {
|
||||
const command = new QueryCommand({
|
||||
TableName: tableName,
|
||||
KeyConditionExpression: keyConditionExpression,
|
||||
...(options?.filterExpression && { FilterExpression: options.filterExpression }),
|
||||
...(options?.expressionAttributeNames && {
|
||||
ExpressionAttributeNames: options.expressionAttributeNames,
|
||||
}),
|
||||
...(options?.expressionAttributeValues && {
|
||||
ExpressionAttributeValues: options.expressionAttributeValues,
|
||||
}),
|
||||
...(options?.indexName && { IndexName: options.indexName }),
|
||||
...(options?.limit && { Limit: options.limit }),
|
||||
...(options?.exclusiveStartKey && { ExclusiveStartKey: options.exclusiveStartKey }),
|
||||
...(options?.scanIndexForward !== undefined && { ScanIndexForward: options.scanIndexForward }),
|
||||
})
|
||||
|
||||
const response = await client.send(command)
|
||||
return {
|
||||
items: (response.Items as Record<string, unknown>[]) || [],
|
||||
count: response.Count || 0,
|
||||
lastEvaluatedKey: response.LastEvaluatedKey as Record<string, unknown> | undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export async function scanItems(
|
||||
client: DynamoDBDocumentClient,
|
||||
tableName: string,
|
||||
options?: {
|
||||
filterExpression?: string
|
||||
projectionExpression?: string
|
||||
expressionAttributeNames?: Record<string, string>
|
||||
expressionAttributeValues?: Record<string, unknown>
|
||||
limit?: number
|
||||
exclusiveStartKey?: Record<string, unknown>
|
||||
}
|
||||
): Promise<{
|
||||
items: Record<string, unknown>[]
|
||||
count: number
|
||||
lastEvaluatedKey?: Record<string, unknown>
|
||||
}> {
|
||||
const command = new ScanCommand({
|
||||
TableName: tableName,
|
||||
...(options?.filterExpression && { FilterExpression: options.filterExpression }),
|
||||
...(options?.projectionExpression && { ProjectionExpression: options.projectionExpression }),
|
||||
...(options?.expressionAttributeNames && {
|
||||
ExpressionAttributeNames: options.expressionAttributeNames,
|
||||
}),
|
||||
...(options?.expressionAttributeValues && {
|
||||
ExpressionAttributeValues: options.expressionAttributeValues,
|
||||
}),
|
||||
...(options?.limit && { Limit: options.limit }),
|
||||
...(options?.exclusiveStartKey && { ExclusiveStartKey: options.exclusiveStartKey }),
|
||||
})
|
||||
|
||||
const response = await client.send(command)
|
||||
return {
|
||||
items: (response.Items as Record<string, unknown>[]) || [],
|
||||
count: response.Count || 0,
|
||||
lastEvaluatedKey: response.LastEvaluatedKey as Record<string, unknown> | undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateItem(
|
||||
client: DynamoDBDocumentClient,
|
||||
tableName: string,
|
||||
key: Record<string, unknown>,
|
||||
updateExpression: string,
|
||||
options?: {
|
||||
expressionAttributeNames?: Record<string, string>
|
||||
expressionAttributeValues?: Record<string, unknown>
|
||||
conditionExpression?: string
|
||||
}
|
||||
): Promise<{ attributes: Record<string, unknown> | null }> {
|
||||
const command = new UpdateCommand({
|
||||
TableName: tableName,
|
||||
Key: key,
|
||||
UpdateExpression: updateExpression,
|
||||
...(options?.expressionAttributeNames && {
|
||||
ExpressionAttributeNames: options.expressionAttributeNames,
|
||||
}),
|
||||
...(options?.expressionAttributeValues && {
|
||||
ExpressionAttributeValues: options.expressionAttributeValues,
|
||||
}),
|
||||
...(options?.conditionExpression && { ConditionExpression: options.conditionExpression }),
|
||||
ReturnValues: 'ALL_NEW',
|
||||
})
|
||||
|
||||
const response = await client.send(command)
|
||||
return {
|
||||
attributes: (response.Attributes as Record<string, unknown>) || null,
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteItem(
|
||||
client: DynamoDBDocumentClient,
|
||||
tableName: string,
|
||||
key: Record<string, unknown>,
|
||||
options?: {
|
||||
conditionExpression?: string
|
||||
expressionAttributeNames?: Record<string, string>
|
||||
expressionAttributeValues?: Record<string, unknown>
|
||||
}
|
||||
): Promise<{ success: boolean }> {
|
||||
const command = new DeleteCommand({
|
||||
TableName: tableName,
|
||||
Key: key,
|
||||
...(options?.conditionExpression && { ConditionExpression: options.conditionExpression }),
|
||||
...(options?.expressionAttributeNames && {
|
||||
ExpressionAttributeNames: options.expressionAttributeNames,
|
||||
}),
|
||||
...(options?.expressionAttributeValues && {
|
||||
ExpressionAttributeValues: options.expressionAttributeValues,
|
||||
}),
|
||||
})
|
||||
|
||||
await client.send(command)
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a raw DynamoDB client for operations that don't require DocumentClient
|
||||
*/
|
||||
export function createRawDynamoDBClient(config: DynamoDBConnectionConfig): DynamoDBClient {
|
||||
return new DynamoDBClient({
|
||||
region: config.region,
|
||||
credentials: {
|
||||
accessKeyId: config.accessKeyId,
|
||||
secretAccessKey: config.secretAccessKey,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all DynamoDB tables in the configured region
|
||||
*/
|
||||
export async function listTables(client: DynamoDBClient): Promise<{ tables: string[] }> {
|
||||
const tables: string[] = []
|
||||
let exclusiveStartTableName: string | undefined
|
||||
|
||||
do {
|
||||
const command = new ListTablesCommand({
|
||||
ExclusiveStartTableName: exclusiveStartTableName,
|
||||
})
|
||||
|
||||
const response = await client.send(command)
|
||||
if (response.TableNames) {
|
||||
tables.push(...response.TableNames)
|
||||
}
|
||||
exclusiveStartTableName = response.LastEvaluatedTableName
|
||||
} while (exclusiveStartTableName)
|
||||
|
||||
return { tables }
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes a specific DynamoDB table and returns its schema information
|
||||
*/
|
||||
export async function describeTable(
|
||||
client: DynamoDBClient,
|
||||
tableName: string
|
||||
): Promise<{ tableDetails: DynamoDBTableSchema }> {
|
||||
const command = new DescribeTableCommand({
|
||||
TableName: tableName,
|
||||
})
|
||||
|
||||
const response = await client.send(command)
|
||||
const table = response.Table
|
||||
|
||||
if (!table) {
|
||||
throw new Error(`Table '${tableName}' not found`)
|
||||
}
|
||||
|
||||
const tableDetails: DynamoDBTableSchema = {
|
||||
tableName: table.TableName || tableName,
|
||||
tableStatus: table.TableStatus || 'UNKNOWN',
|
||||
keySchema:
|
||||
table.KeySchema?.map((key) => ({
|
||||
attributeName: key.AttributeName || '',
|
||||
keyType: (key.KeyType as 'HASH' | 'RANGE') || 'HASH',
|
||||
})) || [],
|
||||
attributeDefinitions:
|
||||
table.AttributeDefinitions?.map((attr) => ({
|
||||
attributeName: attr.AttributeName || '',
|
||||
attributeType: (attr.AttributeType as 'S' | 'N' | 'B') || 'S',
|
||||
})) || [],
|
||||
globalSecondaryIndexes:
|
||||
table.GlobalSecondaryIndexes?.map((gsi) => ({
|
||||
indexName: gsi.IndexName || '',
|
||||
keySchema:
|
||||
gsi.KeySchema?.map((key) => ({
|
||||
attributeName: key.AttributeName || '',
|
||||
keyType: (key.KeyType as 'HASH' | 'RANGE') || 'HASH',
|
||||
})) || [],
|
||||
projectionType: gsi.Projection?.ProjectionType || 'ALL',
|
||||
indexStatus: gsi.IndexStatus || 'UNKNOWN',
|
||||
})) || [],
|
||||
localSecondaryIndexes:
|
||||
table.LocalSecondaryIndexes?.map((lsi) => ({
|
||||
indexName: lsi.IndexName || '',
|
||||
keySchema:
|
||||
lsi.KeySchema?.map((key) => ({
|
||||
attributeName: key.AttributeName || '',
|
||||
keyType: (key.KeyType as 'HASH' | 'RANGE') || 'HASH',
|
||||
})) || [],
|
||||
projectionType: lsi.Projection?.ProjectionType || 'ALL',
|
||||
indexStatus: 'ACTIVE',
|
||||
})) || [],
|
||||
itemCount: Number(table.ItemCount) || 0,
|
||||
tableSizeBytes: Number(table.TableSizeBytes) || 0,
|
||||
billingMode: table.BillingModeSummary?.BillingMode || 'PROVISIONED',
|
||||
}
|
||||
|
||||
return { tableDetails }
|
||||
}
|
||||
Reference in New Issue
Block a user