3
3
const path = require ( 'path' )
4
4
const isImage = require ( 'is-image' )
5
5
const uuid = require ( 'uuid' )
6
+ const mime = require ( 'mime-types' )
7
+ const S3 = require ( 'aws-sdk/clients/s3' )
6
8
const { send } = require ( 'micro' )
7
- const { upload, move } = require ( 'micro-upload' )
9
+ const { upload } = require ( 'micro-upload' )
10
+
11
+ const s3 = new S3 ( {
12
+ region : 'us-west-2' ,
13
+ params : { Bucket : 'medellinjs-microservicios' } ,
14
+ accessKeyId : process . env . AWS_ACCESS_KEY ,
15
+ secretAccessKey : process . env . AWS_SECRET_KEY
16
+ } )
8
17
9
18
//
10
19
// This microservice will be served as /upload
@@ -28,8 +37,22 @@ module.exports = upload(async (req, res) => {
28
37
let ext = path . extname ( file . name )
29
38
let name = uuid . v4 ( ) + ext
30
39
31
- // src: file object, dst: path
32
- await move ( file , path . join ( __dirname , 'uploads' , name ) )
40
+ const result = await s3move ( name , file . data )
33
41
34
- send ( res , 200 , { name : name , src : `/uploads/ ${ name } ` } )
42
+ send ( res , 200 , { name : name , src : result . Location } )
35
43
} )
44
+
45
+ function s3move ( name , data ) {
46
+ return new Promise ( ( resolve , reject ) => {
47
+ s3 . upload ( {
48
+ Key : `uploads/${ name } ` ,
49
+ Body : data ,
50
+ ACL : 'public-read' ,
51
+ ContentType : mime . lookup ( name )
52
+ } , ( err , data ) => {
53
+ if ( err ) return reject ( err )
54
+
55
+ resolve ( data )
56
+ } )
57
+ } )
58
+ }
0 commit comments