Created
July 29, 2020 20:58
-
-
Save gcmatheusj/e0a47971a5f34ae2d30b90b902b8d2ac to your computer and use it in GitHub Desktop.
This file contains 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 sharp = require('sharp'); | |
const crypto = require('crypto'); | |
import awsConfig from '../config/aws'; | |
interface Data { | |
createReadStream: any; | |
filename: string; | |
mimetype: string; | |
} | |
const uploadFile = async ({ | |
createReadStream, | |
filename, | |
mimetype | |
}: Data): Promise<string> => { | |
const allowedMimes = [ | |
'image/jpeg', | |
'image/jpg', | |
'image/pjpeg', | |
'image/png', | |
'image/gif', | |
'image/bmp' | |
]; | |
if (!allowedMimes.includes(mimetype)) { | |
throw new Error('Invalid file type.'); | |
} | |
aws.config.update({ | |
accessKeyId: awsConfig.accessKeyId, | |
secretAccessKey: awsConfig.secretAccessKey | |
}); | |
const s3 = new aws.S3(); | |
const stream = createReadStream().pipe(sharp().resize(800, 800)); | |
const s3Params = { | |
Bucket: awsConfig.bucket, | |
Key: `${crypto.randomBytes(10).toString('HEX')}-${filename}`, | |
ACL: 'public-read', | |
ContentType: mimetype, | |
Body: stream | |
}; | |
const { Location } = await s3.upload(s3Params).promise(); | |
return Location; | |
}; | |
export default uploadFile; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment