]> git.r.bdr.sh - rbdr/captura-backend-example/blob - src/index.js
11e400bd6708e16eae291a045260b254d700b28e
[rbdr/captura-backend-example] / src / index.js
1 const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
2
3 /**
4 * @type {import('aws-lambda').APIGatewayProxyHandler}
5 */
6 module.exports.handler = async (event) => {
7 const data = Buffer.from(event.body, 'base64');
8 let fileExtension;
9 const contentType = event.headers['Content-Type'] || event.headers['content-type'];
10 switch (contentType) {
11 case 'image/gif':
12 fileExtension = 'gif';
13 break;
14 case 'video/mp4':
15 fileExtension = 'mp4';
16 break;
17 default:
18 return {
19 statusCode: 400,
20 body: 'Invalid Content-Type. Expected image/gif or video/mp4.',
21 };
22 }
23
24 const filename = `${Date.now().toString()}.${fileExtension}`;
25
26 const client = new S3Client({});
27 const command = new PutObjectCommand({
28 Bucket: process.env.S3_BUCKET,
29 Key: filename,
30 Body: data,
31 ACL: 'public-read',
32 ContentType: contentType
33 });
34
35 try {
36 await client.send(command);
37
38 return {
39 statusCode: 201,
40 body: JSON.stringify({
41 url: `https://${process.env.DOMAIN_NAME}/${filename}`
42 }),
43 };
44 } catch (error) {
45 console.error(error);
46
47 return {
48 statusCode: 500,
49 body: JSON.stringify({ message: 'Error uploading file.' }),
50 };
51 }
52 };