-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (47 loc) · 1.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
module.exports = {
send: function(fileData, configuration) {
var promise = new Promise(function(resolve, reject){
try {
var file = require('fs').readFileSync(fileData.path)
} catch(error) {
console.error(error);
return reject(error);
}
var headParams = {
Bucket: configuration.bucket,
Key: fileData.name,
}
var uploadParams = Object.assign({
ContentType: fileData.mimetype,
Body: file,
}, headParams)
s3.headObject(headParams, function (err, metadata) {
if (err && err.code === 'NotFound') {
return reallySend(uploadParams, resolve)
}
if (err) {
return console.error(err);
}
console.warn('!!! key collision detected:', params);
});
});
return promise;
},
configuration: {
bucket: process.env.AWS_BUCKET
}
}
function reallySend(params, resolve) {
s3.putObject(params, function(err, data) {
if (err) {
console.log(err);
return reject(err)
}
return resolve({
ETag: data.ETag,
url: `https://${params.Bucket}.s3.amazonaws.com/${params.Key}`,
});
});
}