s3 Bucket

mail@pastecode.io avatar
unknown
javascript
2 months ago
3.5 kB
4
Indexable
Never
const { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand } = require("@aws-sdk/client-s3");
const crypto = require("crypto");
const { getSignedUrl } = require("@aws-sdk/s3-request-presigner");
const { AWS_BUCKET_EXPIRE_TIME } = require("../../config/constants");
const GeneralSettings = require("../models/settings/GeneralSetting");

async function getS3BucketInstance() {
  const generalSettings = await GeneralSettings.findOne();

  if (
    generalSettings?.awsRegion === "" ||
    generalSettings?.awsAccessKeyId === "" ||
    generalSettings?.awsSecretAccessKey === "" ||
    generalSettings?.awsBucketName === ""
  ) {
    throw new Error("Update the AWS S3 Bucket config first!");
  }

  const s3 = new S3Client({
    region: generalSettings?.awsRegion,
    credentials: {
      accessKeyId: generalSettings?.awsAccessKeyId,
      secretAccessKey: generalSettings?.awsSecretAccessKey
    }
  });

  return [s3, generalSettings?.awsBucketName];
}

const randomString = () => {
  return crypto.randomBytes(16).toString("hex");
};

// Upload file to S3 Bucket
const uploadFileToS3Bucket = async (file, folderName) => {
  try {
    const [s3, awsBucketName] = await getS3BucketInstance();
    const buffer = Buffer.from(file.replace(/^data:image\/\w+;base64,/, ""), "base64");
    const Key = `${folderName}/${randomString()}.png`;

    // ======= If you want to resize image use sharp package ======= //
    // const fileBuffer = await sharp(file.buffer)
    // .resize({ height: 1920, width: 1080, fit: "contain" })
    // .toBuffer()

    const params = {
      Bucket: awsBucketName,
      Key,
      Body: buffer,
      ContentEncoding: "base64",
      ContentType: "image/png"
    };

    const command = new PutObjectCommand(params);
    await s3.send(command);

    const imageUrl = `${process.env.S3_BASE_URL}/${Key}`;

    return {
      status: true,
      message: "File uploaded successfully!",
      key: imageUrl
    };
  } catch (error) {
    console.log(error);
    return {
      status: false,
      message: "Something went wrong!"
    };
  }
};

// Get Secure Url From S3 Bucket
const getSecureUrlFromS3Bucket = async (key) => {
  try {
    const [s3, awsBucketName] = await getS3BucketInstance();

    const params = {
      Bucket: awsBucketName,
      Key: key
    };

    const secureUrl = await getSignedUrl(s3, new GetObjectCommand(params), { expiresIn: AWS_BUCKET_EXPIRE_TIME }); // 60 seconds

    return secureUrl;
  } catch (error) {
    console.log(error);
    return null;
  }
};

// Delete File From S3 Bucket
const deleteFileFromS3Bucket = async (key) => {
  try {
    const deleteKey = key.split(`${process.env.S3_BASE_URL}/`);

    if (deleteKey[1].includes("default")) {
      return {
        status: true,
        message: "Default image detected!"
      };
    } else {
      const [s3, awsBucketName] = await getS3BucketInstance();

      const params = {
        Bucket: awsBucketName,
        Key: deleteKey[1]
      };

      const command = new DeleteObjectCommand(params);
      await s3.send(command);

      return {
        status: true,
        message: "File deleted successfully!"
      };
    }
  } catch (error) {
    console.log(error);
    return {
      status: false,
      message: "Something went wrong!"
    };
  }
};

module.exports = {
  uploadFileToS3Bucket,
  deleteFileFromS3Bucket,
  getSecureUrlFromS3Bucket
};
Leave a Comment