Created
June 20, 2022 15:50
-
-
Save miroswd/6028f12572fbcb8b6b2ab7c05586cf91 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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