11import multer from 'multer'
22import crypto from 'crypto'
3+ import aws from 'aws-sdk'
4+ import multerS3 from 'multer-s3'
35import { AppError } from './appError'
46import { httpStatus } from './httpStatus'
57
6- // Ref : https://www.npmjs.com/package/multer
8+ aws . config . update ( { accessKeyId : process . env . AWS_S3_ACCESS_KEY , secretAccessKey : process . env . AWS_S3_SECRET_KEY } )
9+ const s3 = new aws . S3 ( )
710
8- const storage = multer . diskStorage ( {
11+ const diskStorage = multer . diskStorage ( {
912 // Note : You can set your own upload path Ref : https://www.npmjs.com/package/multer#diskstorage
1013 // destination: function (req, file, cb) {},
1114 filename : function ( req , file , cb ) {
@@ -18,11 +21,25 @@ const storage = multer.diskStorage({
1821
1922const limits = { fileSize : parseInt ( process . env . FILE_UPLOAD_SIZE_IN_BYTES ) || 1000000 }
2023
21- const fileFilter = function ( req , file , cb ) {
24+ const imageFileFilter = function ( req , file , cb ) {
2225 if ( ! [ 'image/png' , 'image/jpg' , 'image/jpeg' ] . includes ( file . mimetype ) ) {
2326 return cb ( new AppError ( 'Only jpg,jpeg,png formats are allowed' , httpStatus . UNPROCESSABLE_ENTITY ) )
2427 }
2528 cb ( null , true )
2629}
2730
28- export const upload = multer ( { storage, limits, fileFilter } )
31+ const s3Storage = multerS3 ( {
32+ s3 : s3 ,
33+ bucket : process . env . AWS_S3_BUCKET ,
34+ metadata : function ( req , file , cb ) {
35+ cb ( null , { fieldName : file . fieldname } )
36+ } ,
37+ key : function ( req , file , cb ) {
38+ return crypto . randomBytes ( 16 , function ( err , raw ) {
39+ if ( err ) cb ( err )
40+ cb ( null , process . env . AWS_S3_FILE_UPLOAD_KEY + raw . toString ( 'hex' ) + Date . now ( ) + '.' + file . originalname . split ( '.' ) . pop ( ) . trim ( ) )
41+ } )
42+ }
43+ } )
44+
45+ export { diskStorage , limits , imageFileFilter , s3Storage }
0 commit comments