Write a well written, professional typescript function, that takes a string as param and writes it to dynamodb. This is not a test, not a hobby project, so it needs to be as clean, professional and well written as possible. Use best patterns you think you should use.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a professional TypeScript function for writing to DynamoDB using AWS SDK v3:
typescript
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, PutCommandInput } from "@aws-sdk/lib-dynamodb";
import { v4 as uuidv4 } from 'uuid';
/**
* Configuration interface for DynamoDB operations
*/
interface DynamoDBConfig {
region: string;
tableName: string;
endpoint?: string; // Optional for local development
}
/**
* Interface for the item to be stored in DynamoDB
*/
interface StringRecord {
id: string;
content: string;
createdAt: string;
updatedAt: string;
ttl?: number; // Optional TTL for record expiration
}
/**
* Result interface for write operations
*/
interface WriteResult {
success: boolean;
id?: string;
error?: Error;
}
/**
* Custom error class for DynamoDB operations
*/
class DynamoDBError extends Error {
constructor(message: string, public readonly cause?: Error) {
super(message);
this.name = 'DynamoDBError';
}
}
/**
* DynamoDB writer class encapsulating write operations
*/
export class DynamoDBWriter {
private readonly client: DynamoDBDocumentClient;
private readonly tableName: string;
constructor(config: DynamoDBConfig) {
const baseClient = new DynamoDBClient({
region: config.region,
...(config.endpoint && { endpoint: config.endpoint })
});
this.client = DynamoDBDocumentClient.from(baseClient, {
marshallOptions: {
removeUndefinedValues: true,
convertClassInstanceToMap: true
}
});
this.tableName = config.tableName;
}
/**
* Writes a string to DynamoDB with proper error handling and validation
*
* @param content - The string content to be stored
* @param ttlSeconds - Optional time-to-live in seconds from now
* @returns Promise<WriteResult> - Result object indicating success or failure
*/
async writeString(content: string, ttlSeconds?: number): Promise<WriteResult> {
try {
// Validate input
if (!content || typeof content !== 'string') {
throw new DynamoDBError('Content must be a non-empty string');
}
// Validate content size (DynamoDB item size limit is 400KB)
const contentSize = new TextEncoder().encode(content).length;
if (contentSize > 400 * 1024) {
throw new DynamoDBError(`Content size (${contentSize} bytes) exceeds DynamoDB item limit of 400KB`);
}
const id = uuidv4();
const timestamp = new Date().toISOString();
const item: StringRecord = {
id,
content,
createdAt: timestamp,
updatedAt: timestamp
};
// Add TTL if specified
if (ttlSeconds && ttlSeconds > 0) {
item.ttl = Math.floor(Date.now() / 1000) + ttlSeconds;
}
const params: PutCommandInput = {
TableName: this.tableName,
Item: item,
ConditionExpression: 'attribute_not_exists(id)' // Ensure uniqueness
};
await this.client.send(new PutCommand(params));
return {
success: true,
id
};
} catch (error) {
const dynamoError = error instanceof DynamoDBError
? error
: new DynamoDBError('Failed to write to DynamoDB', error as Error);
return {
success: false,
error: dynamoError
};
}
}
/**
* Batch write multiple strings to DynamoDB
*
* @param contents - Array of strings to be stored
* @returns Promise<WriteResult[]> - Array of results for each write operation
*/
async writeMultipleStrings(contents: string[]): Promise<WriteResult[]> {
const writePromises = contents.map(content => this.writeString(content));
return Promise.all(writePromises);
}
}
/**
* Factory function to create a configured DynamoDB writer instance
*
* @param config - DynamoDB configuration
* @returns DynamoDBWriter instance
*/
export function createDynamoDBWriter(config: Partial<DynamoDBConfig> = {}): DynamoDBWriter {
const finalConfig: DynamoDBConfig = {
region: process.env.AWS_REGION || 'us-east-1',
tableName: process.env.DYNAMODB_TABLE_NAME || 'StringStorage',
...config
};
if (!finalConfig.tableName) {
throw new Error('DynamoDB table name must be provided');
}
return new DynamoDBWriter(finalConfig);
}
/**
* Example usage:
*
* const writer = createDynamoDBWriter({
* region: 'us-east-1',
* tableName: 'MyStringTable'
* });
*
* const result = await writer.writeString('Hello, DynamoDB!');
* if (result.success) {
* console.log(`Successfully wrote string with ID: ${result.id}`);
* } else {
* console.error(`Failed to write string: ${result.error?.message}`);
* }
*/
This implementation includes:
Key Features:
Type Safety: Full TypeScript typing with interfaces for all data structures
Error Handling: Custom error class and comprehensive error handling
Validation: Input validation including size limits
AWS SDK v3: Uses the latest modular SDK for better performance
Clean Architecture: Encapsulated in a class with clear separation of concerns
Configuration: Flexible configuration with environment variable support
UUID Generation: Automatic ID generation for records
TTL Support: Optional time-to-live for automatic record expiration
Batch Operations: Method for writing multiple strings efficiently
Documentation: JSDoc comments for all public methods
Table Schema Requirements:
The DynamoDB table should have:
Primary key: id (String)
Optional TTL attribute: ttl (Number)
Usage Pattern:
typescript
// Initialize once in your application
const writer = createDynamoDBWriter({
region: 'us-east-1',
tableName: 'YourTableName'
});
// Use throughout your application
const result = await writer.writeString('Your content here');
This code follows production best practices including proper error handling, validation, and clean architecture patterns suitable for enterprise applications.