import { S3Client, ListObjectsV2Command, GetObjectCommand, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; const S3: S3Client = new S3Client({}); const bucketName: string = process.env.BUCKET ?? "widget-default-bucket"; export const handler = async function(event: any, context: any): Promise { try { const method: string = event.httpMethod; const widgetName: string = event.path.startsWith('/') ? event.path.substring(1) : event.path; if (method === "GET") { if (event.path === "/") { const data = await S3.send(new ListObjectsV2Command({ Bucket: bucketName })); const body = {widgets: data?.Contents?.map(function(e: any) { return e.Key })}; return { statusCode: 200, headers: {}, body: JSON.stringify(body) }; } if (widgetName) { const data = await S3.send(new GetObjectCommand({ Bucket: bucketName, Key: widgetName})); const body = data?.Body?.toString(); //'utf-8'); return { statusCode: 200, headers: {}, body: JSON.stringify(body) }; } } if (method === "POST") { if (!widgetName) { return { statusCode: 400, headers: {}, body: "Widget name missing" }; } const now: Date = new Date(); const data: string = widgetName + " created: " + now; const base64data: Buffer = Buffer.from(data, 'binary'); await S3.send(new PutObjectCommand({ Bucket: bucketName, Key: widgetName, Body: base64data, ContentType: 'application/json' })); return { statusCode: 200, headers: {}, body: data }; } if (method === "DELETE") { if (!widgetName) { return { statusCode: 400, headers: {}, body: "Widget name missing" }; } await S3.send(new DeleteObjectCommand({ Bucket: bucketName, Key: widgetName })); return { statusCode: 200, headers: {}, body: "Successfully deleted widget " + widgetName }; } return { statusCode: 400, headers: {}, body: "We only accept GET, POST, and DELETE, not " + method }; } catch(error) { var body = error.stack || JSON.stringify(error, null, 2); return { statusCode: 400, headers: {}, body: body } } }