HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/good-life-be/modules/s3/index.js
import {
  DeleteObjectCommand,
  GetObjectCommand,
  PutObjectCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import s3 from '../../config/s3-config.js';
import BadRequest from '../../helper/exception/badRequest.js';
import RandomFilename from '../../helper/randomFileName.js';

export async function uploadToS3(key, body, contentType) {
  try {
    const randomKey = RandomFilename(key);

    const year = new Date().getFullYear();

    const month = `0${new Date().getMonth() + 1}`.slice(-2);

    // Add project folder to the path
    const uploadPath = `calendar/${year}/${month}/${randomKey}`;

    console.log('uploadPath', uploadPath);

    const options = {
      Bucket: process.env.S3_BUCKET_NAME,
      Key: uploadPath,
      Body: body,
      ContentType: contentType,
    };
    console.log('options', options);

    await s3.send(new PutObjectCommand(options));

    return uploadPath;
  } catch (e) {
    throw new BadRequest('Failed to upload image', 'IMAGE_UPLOAD_FAILED');
  }
}

export async function deleteFromS3(key) {
  try {
    const options = {
      Bucket: process.env.S3_BUCKET_NAME,
      Key: key,
    };
    await s3.send(new DeleteObjectCommand(options));
  } catch (e) {
    throw new BadRequest('Failed to fetch image', 'IMAGE_GET_FAILED');
  }
}

export async function getS3SignedUrl(key) {
  return getSignedUrl(
    s3,
    new GetObjectCommand({ Bucket: process.env.S3_BUCKET_NAME, Key: key }),
    {
      expiresIn: 3600,
    }
  );
}