aboutsummaryrefslogtreecommitdiff
path: root/src/index.js
blob: 11e400bd6708e16eae291a045260b254d700b28e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');

/**
 * @type {import('aws-lambda').APIGatewayProxyHandler}
 */
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.' }),
    };
  }
};