import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import {
DynamoDBDocumentClient,
GetCommand,
PutCommand,
ScanCommand,
DeleteCommand,
UpdateCommand,
} from '@aws-sdk/lib-dynamodb';
import { v4 as uuidv4 } from 'uuid';
const client = new DynamoDBClient({});
const ddbDocClient = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.TABLE_NAME;
const corsHeaders = () => ({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Methods': 'OPTIONS,GET,POST,PUT,DELETE',
});
const createError = (statusCode, message) => {
const error = new Error(message);
error.statusCode = statusCode;
return error;
};
const getTodo = async (id) => {
if (!id || typeof id !== 'string' || id.trim() === '') {
throw createError(400, 'Invalid or missing todo ID');
}
const command = new GetCommand({
TableName: TABLE_NAME,
Key: { id: id.trim() },
});
const result = await ddbDocClient.send(command);
if (!result.Item) {
throw createError(404, 'Todo not found');
}
return result.Item;
};
const listTodos = async () => {
const command = new ScanCommand({ TableName: TABLE_NAME });
const result = await ddbDocClient.send(command);
return result.Items || [];
};
const createTodo = async (input) => {
if (!input?.text || typeof input.text !== 'string' || input.text.trim() === '') {
throw createError(400, 'Missing or invalid "text" field');
}
const id = uuidv4();
const item = {
id,
text: input.text.trim(),
completed: !!input.completed,
createdAt: new Date().toISOString(),
};
const command = new PutCommand({
TableName: TABLE_NAME,
Item: item,
ConditionExpression: 'attribute_not_exists(id)',
});
try {
await ddbDocClient.send(command);
return item;
} catch (error) {
if (error.name === 'ConditionalCheckFailedException') {
throw createError(409, 'Todo with this ID already exists');
}
throw error;
}
};
const updateTodo = async (id, input) => {
if (!id || typeof id !== 'string' || id.trim() === '') {
throw createError(400, 'Invalid or missing todo ID');
}
if (!input || typeof input !== 'object' || Object.keys(input).length === 0) {
throw createError(400, 'No update data provided');
}
// Build dynamic UpdateExpression for partial updates
const keys = Object.keys(input);
const updateExpression = `SET ${keys.map((k) => `#${k} = :${k}`).join(', ')}`;
const expressionAttributeNames = keys.reduce((acc, k) => ({ ...acc, [`#${k}`]: k }), {});
const expressionAttributeValues = keys.reduce((acc, k) => ({ ...acc, [`:${k}`]: input[k] }), {});
const command = new UpdateCommand({
TableName: TABLE_NAME,
Key: { id: id.trim() },
UpdateExpression: updateExpression,
ExpressionAttributeNames: expressionAttributeNames,
ExpressionAttributeValues: expressionAttributeValues,
});
await ddbDocClient.send(command);
return { id: id.trim(), message: 'Todo updated successfully' };
};
const deleteTodo = async (id) => {
if (!id || typeof id !== 'string' || id.trim() === '') {
throw createError(400, 'Invalid or missing todo ID');
}
const command = new DeleteCommand({
TableName: TABLE_NAME,
Key: { id: id.trim() },
});
await ddbDocClient.send(command);
return { message: 'Todo deleted successfully' };
};
export const handler = async (event) => {
const { httpMethod, pathParameters, body } = event;
// Handle CORS preflight
if (httpMethod === 'OPTIONS') {
return {
statusCode: 200,
headers: corsHeaders(),
body: '',
};
}
try {
let response;
switch (httpMethod) {
case 'GET':
if (pathParameters?.id) {
response = await getTodo(pathParameters.id);
} else {
response = await listTodos();
}
break;
case 'POST':
const createData = body ? JSON.parse(body) : {};
response = await createTodo(createData);
break;
case 'PUT':
if (!pathParameters?.id) {
throw createError(400, 'Missing todo ID for update');
}
const updateData = body ? JSON.parse(body) : {};
response = await updateTodo(pathParameters.id, updateData);
break;
case 'DELETE':
if (!pathParameters?.id) {
throw createError(400, 'Missing todo ID for delete');
}
response = await deleteTodo(pathParameters.id);
break;
default:
throw createError(405, `Unsupported method: ${httpMethod}`);
}
return {
statusCode: 200,
headers: corsHeaders(),
body: JSON.stringify(response),
};
} catch (error) {
console.error('Handler error:', error);
const statusCode = error.statusCode || 500;
return {
statusCode,
headers: corsHeaders(),
body: JSON.stringify({ error: error.message }),
};
}
};