Last active
January 23, 2020 23:29
-
-
Save ibejohn818/256fe0fb20921e5d210192e0ea8324e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import express from 'express' | |
| const app = express() | |
| import AWS from 'aws-sdk' | |
| const fs = require('fs') | |
| const path = require('path') | |
| const mtype = require('mime-types') | |
| const BUCKET = "mt-jhardy" | |
| const PORT = 8080 | |
| const s3 = new AWS.S3({'region': 'us-west-2'}) | |
| /** | |
| * Test upload function to set CacheControl on javascript uploads | |
| */ | |
| const uploadFile = async (filePath, Key) => { | |
| try { | |
| // read file path to byte array | |
| const Body = fs.readFileSync(filePath) | |
| // lookup mime-type | |
| const ContentType = mtype.lookup(filePath) | |
| const p = { | |
| Bucket: BUCKET, | |
| Body, | |
| Key, | |
| ContentType, | |
| } | |
| switch (ContentType) { | |
| case 'application/javascript': | |
| p['CacheControl'] = "public, max-age=96000000" | |
| break; | |
| default: | |
| break; | |
| } | |
| const res = await s3.putObject(p).promise() | |
| return res | |
| } catch (err) { | |
| console.error("Error: ", err) | |
| } | |
| } | |
| /** | |
| * Index endpoint | |
| */ | |
| app.all("/", (req, res) => { | |
| const msg = ['Uploaded: '] | |
| let files = [ | |
| "/tmp/jh.js", | |
| "/tmp/test.css", | |
| "/tmp/test.jpg" | |
| ] | |
| files.map((f) => { | |
| let key = `test/${path.basename(f)}` | |
| let result = uploadFile(f, key) | |
| msg.push(`\t - File: ${f} -> s3://${BUCKET}/${key}`) | |
| }) | |
| res.send(msg.join('<br />')) | |
| }) | |
| // start server on PORT | |
| app.listen(PORT,()=> | |
| console.log(`Server is listening on port: ${PORT}`)) | |
| module.exports = app; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const uploadFile = async (Key, Body, ContentType) => { | |
| try { | |
| const params = { | |
| Body, | |
| Bucket: AWS_STATIC_BUCKET_NAME, | |
| Key, | |
| ContentType, | |
| ACL: 'public-read', | |
| } | |
| switch (ContentType) { // set CacheControl based on mime-type | |
| case 'application/javascript': | |
| params['CacheControl'] = 'public, max-age=31622400' | |
| break; | |
| default: | |
| // do nothing | |
| break; | |
| } | |
| await s3.putObject(params).promise() | |
| logger.info(`S3 Uploaded File: ${Key} as ${ContentType}`) | |
| return | |
| } catch (err) { | |
| throw err | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment