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