Skip to content

Instantly share code, notes, and snippets.

@christianhaller
Created December 6, 2020 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianhaller/021a60a680c84d5038a19387e2d64952 to your computer and use it in GitHub Desktop.
Save christianhaller/021a60a680c84d5038a19387e2d64952 to your computer and use it in GitHub Desktop.
Upload files to S3 and invalidate CF
const { S3, CloudFront } = require("aws-sdk");
const { promises } = require("fs");
const globby = require("globby");
const { lookup } = require("mime-types");
const { extname, join } = require("path");
(async () => {
const files = await globby("*", { cwd: "dist" });
const Bucket = "www.fabiangroher.de";
const DistributionId = "EL7ZW9DN9Q7WC";
const toUpload = await Promise.all(
files.map(async (file) => {
return {
Key: file,
Body: await promises.readFile(join("dist", file)),
};
})
);
const s3 = new S3();
await Promise.all(
toUpload.map((file) => {
const ext = extname(file.Key);
const CacheControl =
ext === ".html"
? " max-age=600, s-maxage=600, public"
: "max-age=31104000, s-maxage=3600, immutable, public";
return s3
.putObject({
Bucket,
...file,
CacheControl,
ContentType: lookup(file.Key),
})
.promise();
})
);
const res = await new CloudFront()
.createInvalidation({
DistributionId,
InvalidationBatch: {
CallerReference: Date.now().toString(),
Paths: {
Quantity: 1,
Items: ["/*"],
},
},
})
.promise();
console.log(`${files.join(", ")} uploaded to ${Bucket} 💪🏼`);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment