forked from LalitKushwah/IglooServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3helpers.js
77 lines (66 loc) · 1.67 KB
/
s3helpers.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const uuidv1 = require('uuid/v1')
async function createS3UUID(s3, bucketname, extension) {
let uuid = ''
while (uuid === '') {
uuid = uuidv1() + extension
await new Promise((resolve, reject) => {
s3.headObject({ Bucket: bucketname, Key: uuid }, (err, data) => {
if (!err) {
// the object already exist, try again
uuid = ''
resolve()
} else if (err.code === 'NotFound') {
// the object doesn't already exist
resolve()
} else {
console.log(err)
reject(err)
}
})
})
}
return uuid
}
function s3UploadPromise(s3, uploadParams) {
return new Promise((resolve, reject) => {
s3.upload(uploadParams, (err, data) => {
if (err) {
reject(err)
}
if (data) {
resolve(data)
}
})
})
}
async function pipeStreamToS3(s3, bucketName, stream, extension, userId) {
// call S3 to retrieve upload file to specified bucket
const uploadParams = {
Bucket: bucketName,
Key: '',
Body: '',
Metadata: { userId },
}
stream.on('error', (err) => {
console.log('stream Error', err)
})
uploadParams.Body = stream
uploadParams.Key = await createS3UUID(s3, bucketName, extension) // call S3 to retrieve upload file to specified bucket
const newObject = await s3UploadPromise(s3, uploadParams)
return newObject
}
function getObjectOwner(s3, getParams) {
return new Promise((resolve, reject) => {
s3.headObject(getParams, (err, data) => {
if (err) {
reject(err)
} else {
resolve(data.Metadata.userid)
}
})
})
}
module.exports = {
pipeStreamToS3,
getObjectOwner,
}