Skip to content

Instantly share code, notes, and snippets.

@miroswd
Created June 20, 2022 15:50
Show Gist options
  • Save miroswd/6028f12572fbcb8b6b2ab7c05586cf91 to your computer and use it in GitHub Desktop.
Save miroswd/6028f12572fbcb8b6b2ab7c05586cf91 to your computer and use it in GitHub Desktop.
const aws = require('aws-sdk');
const mime = require('mime');
const path = require('path');
const fs = require('fs');
const multerConfig = require('../../config/multerConfig');
const { AWS_BUCKET_REGION, AWS_BUCKET } = process.env;
module.exports = class S3Storage {
constructor() {
this.client = new aws.S3({
region: AWS_BUCKET_REGION,
})
}
async saveFile(filename) {
const originalPath = path.resolve(multerConfig.directory, filename)
const ContentType = mime.getType(originalPath);
if (!ContentType) {
throw new Error("File not found")
}
const fileContent = await fs.promises.readFile(originalPath);
this.client.putObject({
Bucket: AWS_BUCKET,
Key: filename,
ACL: 'public-read',
Body: fileContent,
ContentType,
}).promise();
await fs.promises.unlink(originalPath)
}
async deleteFile(filename) {
await this.client.deleteObject({
Bucket: AWS_BUCKET,
Key: filename,
}).promise();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment