Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement