File

src/common/provider/storage/s3.ts

Index

Methods

Methods

Async getFileByKey
getFileByKey(filename: string)
Parameters :
Name Type Optional
filename string No
Returns : unknown
getS3
getS3()
Returns : any
Async upload
upload(file: IFile, key: string)
Parameters :
Name Type Optional
file IFile No
key string No
Returns : unknown
Async uploadS3
uploadS3(base64String: string, fileType: string, bucket: string, key: string)
Parameters :
Name Type Optional
base64String string No
fileType string No
bucket string No
key string No
Returns : unknown
import { S3 } from "aws-sdk";
import { Injectable, ServiceUnavailableException } from "@nestjs/common";

import type { IFile } from "../../interfaces";

@Injectable()
export class S3Service {
  async upload(file: IFile, key: string) {
    const s3Bucket = process.env.S3_BUCKET;

    return await this.uploadS3(file.base64String, file.fileType, s3Bucket, key);
  }

  async uploadS3(
    base64String: string,
    fileType: string,
    bucket: string,
    key: string,
  ) {
    try {
      const s3 = this.getS3();
      const base64Data = base64String.replace(`data:${fileType};base64,`, "");
      const buffer = Buffer.from(base64Data, "base64");

      const params = {
        Bucket: bucket,
        Key: String(key),
        Body: buffer,
        ContentType: fileType,
      };

      await s3.upload(params).promise();

      return key;
    } catch (error) {
      console.error(error);
      throw new ServiceUnavailableException(error);
    }
  }

  async getFileByKey(filename: string) {
    try {
      const s3 = this.getS3();
      const s3Bucket = process.env.S3_BUCKET;
      const params = {
        Bucket: s3Bucket,
        Key: filename,
        Expires: 60 * 60 * 24 * 7,
      };
      const url = await s3.getSignedUrlPromise("getObject", params);
      return url;
    } catch (error) {
      console.log("error: getSignedUrl: ", error);
      return ""; // return default image?
    }
  }
  getS3() {
    return new S3({
      signatureVersion: "v4",
      endpoint: "s3-eu-west-2.amazonaws.com",
      region: "eu-west-2",
    });
  }
}

results matching ""

    No results matching ""