Skip to content

Instantly share code, notes, and snippets.

@joebui
Last active September 29, 2019 16:34
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 joebui/333902efbde2821df54e3260e20a3c31 to your computer and use it in GitHub Desktop.
Save joebui/333902efbde2821df54e3260e20a3c31 to your computer and use it in GitHub Desktop.
'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