UNPKG

industry-tools

Version:

Industry Tools is a TypeScript library providing essential tools for the Industry AI Agent Platform.

76 lines (75 loc) 2.81 kB
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DeleteCommand, DynamoDBDocumentClient, GetCommand, PutCommand, QueryCommand, ScanCommand, UpdateCommand } from "@aws-sdk/lib-dynamodb"; import { ToolStorage } from "./ToolStorage"; export class DynamoToolStorage extends ToolStorage { constructor(region, tableName) { super(); const dbClient = new DynamoDBClient({ region }); this.client = DynamoDBDocumentClient.from(dbClient, { marshallOptions: { convertEmptyValues: true, removeUndefinedValues: true, convertClassInstanceToMap: true, }, }); this.tableName = tableName; } async getItem(pk, sk) { const params = { TableName: this.tableName, Key: { PK: pk, SK: sk }, }; return (await this.client.send(new GetCommand(params))).Item; } async createItem(pk, sk, props) { const params = { TableName: this.tableName, Item: { PK: pk, SK: sk, ...props }, }; await this.client.send(new PutCommand(params)); } async deleteItem(pk, sk) { const params = { TableName: this.tableName, Key: { PK: pk, SK: sk }, }; await this.client.send(new DeleteCommand(params)); } async updateItem(pk, sk, updateValues) { let updateExpression = "set "; const expressionAttributeNames = {}; const expressionAttributeValues = {}; for (const [k, v] of Object.entries(updateValues)) { updateExpression += `#${k} = :${k}, `; expressionAttributeNames[`#${k}`] = k; expressionAttributeValues[`:${k}`] = v; } updateExpression = updateExpression.slice(0, -2); const params = { TableName: this.tableName, Key: { PK: pk, SK: sk }, UpdateExpression: updateExpression, ExpressionAttributeNames: expressionAttributeNames, ExpressionAttributeValues: expressionAttributeValues, }; await this.client.send(new UpdateCommand(params)); } async query(expression) { const params = { TableName: this.tableName, KeyConditionExpression: expression.condition, ExpressionAttributeValues: expression.values, }; const data = await this.client.send(new QueryCommand(params)); return data.Items; } async scan(expression) { const params = { TableName: this.tableName, FilterExpression: expression.filter, ExpressionAttributeValues: expression.values, }; const data = await this.client.send(new ScanCommand(params)); return data.Items; } }