forked from koyeb-community/file-replicator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-replicator.js
65 lines (55 loc) · 1.77 KB
/
file-replicator.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
/** @format */
"use strict";
const S3 = require("aws-sdk/clients/s3");
const getS3Configuration = (bucket) => {
return {
accessKeyId: process.env[`KOYEB_STORE_${bucket}_ACCESS_KEY`],
secretAccessKey: process.env[`KOYEB_STORE_${bucket}_SECRET_KEY`],
region: process.env[`KOYEB_STORE_${bucket}_REGION`],
endpoint: process.env[`KOYEB_STORE_${bucket}_ENDPOINT`],
};
};
const validateEnvironment = (bucket) => {
if (!bucket) {
throw new Error("Bucket name not present in event payload.");
}
if (
!process.env?.[`KOYEB_STORE_${bucket}_ACCESS_KEY`] ||
!process.env?.[`KOYEB_STORE_${bucket}_SECRET_KEY`] ||
!process.env[`KOYEB_STORE_${bucket}_REGION`] ||
!process.env[`KOYEB_STORE_${bucket}_ENDPOINT`]
) {
throw new Error(
`One of the following environment variables are missing: KOYEB_STORE_${bucket}_ACCESS_KEY, KOYEB_STORE_${bucket}_SECRET_KEY, KOYEB_STORE_${bucket}_ENDPOINT, KOYEB_STORE_${bucket}_REGION.`
);
}
};
const handler = async (event) => {
const sourceBucket = event?.bucket?.name;
const destinatonBucket = process.env.DESTINATION_STORE;
const key = event?.object?.key;
validateEnvironment(sourceBucket);
validateEnvironment(destinatonBucket);
const s3InstanceSrc = new S3(getS3Configuration(sourceBucket));
const s3InstanceDst = new S3(getS3Configuration(destinatonBucket));
try {
const response = await s3InstanceSrc
.getObject({
Bucket: bucket,
Key: key,
})
.promise();
await s3InstanceDst
.upload({
Bucket: destinatonBucket,
Key: key,
Body: response.Body,
ContentType: response.ContentType,
Metadata: response.Metadata,
})
.promise();
} catch (error) {
throw error;
}
};
module.exports.handler = handler;