image-optimizer-s3-fastcodeco
Version:
IMAGE OPTIMIZER FASTCODE CO --
81 lines (67 loc) • 2.4 kB
text/typescript
import { PutObjectCommand, PutObjectCommandInput, S3Client, S3ClientConfig } from "@aws-sdk/client-s3"
import { UploadS3_IMGUP } from "../types";
/**
* Handle upload to S3
*
*/
export class uploadS3{
private region:string;
private accessKey:string;
private secretKey:string;
private bucket_name:string;
private aws_url:string;
/**
*
* @param region
* @param accessKey
* @param secretKey
* @param bucket_name
* @param aws_url
*/
constructor(region:string, accessKey:string, secretKey:string, bucket_name:string, aws_url?:string){
this.region = region;
this.accessKey = accessKey;
this.secretKey = secretKey;
this.bucket_name = bucket_name;
this.aws_url = aws_url || "https://{{bucket_name}}.s3.{{region}}.amazonaws.com";
}
/**
*
* @returns
*/
private s3Client():S3Client{
const clientParams: S3ClientConfig = {
region: this.region,
credentials: {
accessKeyId: this.accessKey,
secretAccessKey: this.secretKey
}
}
return new S3Client(clientParams);
}
/**
* @function
* @name uploadFileAWSService
* @description Service to upload a file to AWS.
* @param { Buffer } buffer
* @param { string } key
* @returns { Promise }
*/
public upload(buffer: Buffer, filename: string):Promise<UploadS3_IMGUP>{
return new Promise(async (resolve, reject) => {
try {
const client = this.s3Client();
const uploadParams: PutObjectCommandInput = {
Bucket: this.bucket_name,
Key: filename,
Body: buffer
};
await client.send(new PutObjectCommand(uploadParams));
const url = `${this.aws_url.replace("{{bucket_name}}", this.bucket_name).replace("{{region}}", this.region)}/${filename}`;
resolve({ ok: true, url })
} catch (error) {
reject({ok:false, error:error});
}
});
}
}