forked from pulumi/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmake-s3-redirects.js
82 lines (64 loc) · 2.74 KB
/
make-s3-redirects.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
const { PutObjectCommand, S3Client } = require("@aws-sdk/client-s3");
const fs = require("fs");
const bucket = process.argv[2];
const redirectsFile = process.argv[3] || "./public/redirects.txt";
const region = process.argv[4] || "us-west-2"
async function doRedirects(bucket, region) {
const redirects = fs.readFileSync(redirectsFile, "utf-8").trim().split("\n");
console.log(`Processing ${redirects.length} redirects...`);
const client = new S3Client({ region, endpoint: `https://s3.${region}.amazonaws.com` });
// Chunk requests into groups of a thousand to process them more efficiently.
const chunkSize = 1000;
const chunks = [];
const results = [];
for (let i = 0; i < redirects.length; i += chunkSize) {
chunks.push({ chunk: i / chunkSize, lines: redirects.slice(i, i + chunkSize) });
}
for await (const chunk of chunks) {
console.log(` ↳ Processing group ${chunk.chunk + 1} of ${chunks.length} (${chunk.lines.length} URLs)...`);
const result = await Promise.allSettled(chunk.lines.map(line => {
const [ key, location ] = line.split("|");
return new Promise(async (resolve, reject) => {
try {
console.log(` ↳ Redirecting ${key} to ${location}`);
const command = new PutObjectCommand({
Bucket: bucket,
Key: key,
WebsiteRedirectLocation: location,
ACL: "public-read",
Body: "",
ContentLength: 0,
});
const res = await client.send(command);
const status = res.$metadata.httpStatusCode;
if (status < 400) {
resolve(status);
} else {
reject(status);
}
}
catch (error) {
reject(`Error redirecting ${key}: ${error}`);
}
});
}));
results.push(...result);
}
return results;
}
doRedirects(bucket, region)
.then(results => {
const summary = {
checked: results.length,
fulfilled: results.filter(r => r.status === "fulfilled").map(r => r.value) || [],
rejected: results.filter(r => r.status === "rejected").map(r => r.reason) || [],
};
console.log(" ↳ Done. ✨\n");
if (summary.rejected.length > 0) {
throw new Error(`One or more redirects failed: \n\n${summary.rejected.join("\n")}\n`);
}
});
// Exit non-zero when something goes wrong in the promise chain.
process.on("unhandledRejection", error => {
throw new Error(error);
});