forked from aws-samples/amazon-cloudfront-secure-static-site
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwitch.js
106 lines (90 loc) · 2.65 KB
/
witch.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const fs = require('node:fs');
const path = require('node:path');
const mime = require('mime-types');
const https = require('node:https');
const url = require('node:url');
const s3Client = new S3Client();
const SUCCESS = 'SUCCESS';
const FAILED = 'FAILED';
const { BUCKET } = process.env;
exports.staticHandler = (event, context) => {
if (event.RequestType !== 'Create' && event.RequestType !== 'Update') {
return respond(event, context, SUCCESS, {});
}
Promise.all(
walkSync('./').map((file) => {
const fileType = mime.lookup(file) || 'application/octet-stream';
console.log(`${file} -> ${fileType}`);
return s3Client.send(
new PutObjectCommand({
Body: fs.createReadStream(file),
Bucket: BUCKET,
ContentType: fileType,
Key: file,
ACL: 'private',
})
);
})
)
.then((msg) => {
respond(event, context, SUCCESS, {});
})
.catch((err) => {
respond(event, context, FAILED, { Message: err });
});
};
// List all files in a directory in Node.js recursively in a synchronous fashion
function walkSync(dir, filelist = []) {
const files = fs.readdirSync(dir);
files.forEach(function (file) {
if (fs.statSync(path.join(dir, file)).isDirectory()) {
filelist = walkSync(path.join(dir, file), filelist);
} else {
filelist.push(path.join(dir, file));
}
});
return filelist;
}
function respond(
event,
context,
responseStatus,
responseData,
physicalResourceId,
noEcho
) {
const responseBody = JSON.stringify({
Status: responseStatus,
Reason: `See the details in CloudWatch Log Stream: ${context.logStreamName}`,
PhysicalResourceId: physicalResourceId || context.logStreamName,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
NoEcho: noEcho || false,
Data: responseData,
});
console.log('Response body:\n', responseBody);
const { pathname, hostname, search } = new url.URL(event.ResponseURL);
const options = {
hostname,
port: 443,
path: pathname + search,
method: 'PUT',
headers: {
'content-type': '',
'content-length': responseBody.length,
},
};
const request = https.request(options, (response) => {
console.log(`Status code: ${response.statusCode}`);
console.log(`Status message: ${response.statusMessage}`);
context.done();
});
request.on('error', (error) => {
console.log(`send(..) failed executing https.request(..): ${error}`);
context.done();
});
request.write(responseBody);
request.end();
}