]>
Commit | Line | Data |
---|---|---|
08b55c6d RBR |
1 | const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3'); |
2 | ||
b6c1559c E |
3 | /** |
4 | * @type {import('aws-lambda').APIGatewayProxyHandler} | |
5 | */ | |
08b55c6d RBR |
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 | }; |