Last active
September 29, 2019 16:34
-
-
Save joebui/333902efbde2821df54e3260e20a3c31 to your computer and use it in GitHub Desktop.
This file contains 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
'use strict'; | |
const AWS = require('aws-sdk'); | |
const s3 = new AWS.S3(); | |
exports.handler = async event => { | |
const request = event.Records[0].cf.request; | |
try { | |
if (request.uri && request.headers['accept-encoding']) { | |
const acceptEncoding = request.headers['accept-encoding'][0].value; | |
// Check brotli support. | |
if (acceptEncoding.includes('br')) { | |
await applyPrecompressedAsset('br', request); | |
} else { | |
// Check gzip support. | |
if (acceptEncoding.includes('gzip')) { | |
await applyPrecompressedAsset('gz', request); | |
} | |
} | |
} | |
} catch (e) { | |
console.log(`Error occurred with ${request.uri}: ${JSON.stringify(e)}`); | |
} finally { | |
return request; | |
} | |
}; | |
function isFileExisted(uri) { | |
// Remember to grant IAM's S3 read permission to the Lambda | |
// for this to work. | |
return s3.headObject({ Bucket: 'bucket-name', Key: uri }).promise(); | |
} | |
async function applyPrecompressedAsset(ext, request) { | |
const newUri = `${request.uri}.${ext}`; | |
await isFileExisted(newUri.substr(1)); | |
request.uri = newUri; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment