Skip to content

Instantly share code, notes, and snippets.

@gcmatheusj
Created July 29, 2020 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcmatheusj/e0a47971a5f34ae2d30b90b902b8d2ac to your computer and use it in GitHub Desktop.
Save gcmatheusj/e0a47971a5f34ae2d30b90b902b8d2ac to your computer and use it in GitHub Desktop.
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