diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/index.js | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..bae1fc0 --- /dev/null +++ b/src/index.js @@ -0,0 +1,49 @@ +const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3'); + +module.exports.handler = async (event) => { + const data = Buffer.from(event.body, 'base64'); + let fileExtension; + const contentType = event.headers['Content-Type'] || event.headers['content-type']; + switch (contentType) { + case 'image/gif': + fileExtension = 'gif'; + break; + case 'video/mp4': + fileExtension = 'mp4'; + break; + default: + return { + statusCode: 400, + body: 'Invalid Content-Type. Expected image/gif or video/mp4.', + }; + } + + const filename = `${Date.now().toString()}.${fileExtension}`; + + const client = new S3Client({}); + const command = new PutObjectCommand({ + Bucket: process.env.S3_BUCKET, + Key: filename, + Body: data, + ACL: 'public-read', + ContentType: contentType + }); + + try { + await client.send(command); + + return { + statusCode: 201, + body: JSON.stringify({ + url: `https://${process.env.DOMAIN_NAME}/${filename}` + }), + }; + } catch (error) { + console.error(error); + + return { + statusCode: 500, + body: JSON.stringify({ message: 'Error uploading file.' }), + }; + } +}; |