-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuploadToS3.js
66 lines (59 loc) · 1.92 KB
/
uploadToS3.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
const fs = require("fs");
const aws = require("aws-sdk");
const shortid = require("shortid");
const envVariable = require("./config");
const s3Stream = require("s3-upload-stream");
const mimetype = require("mime-types");
const s3 = new aws.S3({
apiVersion: "2006-03-01",
region: envVariable.region,
accessKeyId: envVariable.accessKey,
secretAccessKey: envVariable.secretKey,
});
const upload = async (thumbnail, companyId, customExt = "") =>
new Promise((resolve, reject) => {
// Allow uploading of files with custom extensions
const key = `${Date.now()}-${shortid.generate()}.${customExt || "pdf"}`;
const media = fs.createReadStream(thumbnail);
const contentType = mimetype.lookup(thumbnail);
const upload = s3Stream(s3).upload({
Bucket: envVariable.bucketName,
Key: `${companyId}/${key}`,
ACL: "public-read",
StorageClass: "REDUCED_REDUNDANCY",
ContentType: contentType,
});
media.pipe(upload);
upload.on("error", (err) => {
try {
console.log("encountered error", thumbnail);
console.log("---");
console.log(err);
console.log("---");
fs.unlink(thumbnail, () => {});
} catch (err) {
console.log("encountered error - upload.on catch");
console.log(err);
//ignore
}
reject();
});
upload.on("uploaded", () => {
console.info("uploaded successfully!");
try {
fs.unlink(thumbnail, () => {});
} catch (err) {
console.log(err);
//ignore
}
let thumbnailUrl = `https://${envVariable.bucketName}.s3.amazonaws.com/${companyId}/${key}`;
resolve(thumbnailUrl);
});
});
const uploadThumbnails = async (thumbnails, companyId, customExt = "") => {
const thumbnailUrls = await Promise.all(
thumbnails.map((thumbnail) => upload(thumbnail, companyId, customExt))
);
return thumbnailUrls;
};
module.exports = { upload, uploadThumbnails };