import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, ScanCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
const TABLE_NAME = "ItemsTable";
export const handler = async (event) => {
const method = event.requestContext?.http?.method || event.httpMethod;
try {
if (method === "GET") {
const data = await docClient.send(new ScanCommand({ TableName: TABLE_NAME }));
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data.Items)
};
}
if (method === "POST") {
const body = JSON.parse(event.body || "{}");
await docClient.send(new PutCommand({
TableName: TABLE_NAME,
Item: {
id: body.id || Date.now().toString(),
name: body.name || "Default Item",
createdAt: new Date().toISOString()
}
}));
return {
statusCode: 201,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "Item created successfully" })
};
}
return { statusCode: 405, body: "Method Not Allowed" };
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: error.message })
};
}
};
Loading article