Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. 'use strict';
  2.  
  3. const AWS = require('aws-sdk');
  4. const s3 = new AWS.S3();
  5.  
  6. exports.handler = async event => {
  7. const request = event.Records[0].cf.request;
  8.  
  9. try {
  10. if (request.uri && request.headers['accept-encoding']) {
  11. const acceptEncoding = request.headers['accept-encoding'][0].value;
  12.  
  13. // Check brotli support.
  14. if (acceptEncoding.includes('br')) {
  15. await applyPrecompressedAsset('br', request);
  16. } else {
  17. // Check gzip support.
  18. if (acceptEncoding.includes('gzip')) {
  19. await applyPrecompressedAsset('gz', request);
  20. }
  21. }
  22. }
  23. } catch (e) {
  24. console.log(`Error occurred with ${request.uri}: ${JSON.stringify(e)}`);
  25. } finally {
  26. return request;
  27. }
  28. };
  29.  
  30. function isFileExisted(uri) {
  31. // Remember to grant IAM's S3 read permission to the Lambda
  32. // for this to work.
  33. return s3.headObject({ Bucket: 'bucket-name', Key: uri }).promise();
  34. }
  35.  
  36. async function applyPrecompressedAsset(ext, request) {
  37. const newUri = `${request.uri}.${ext}`;
  38. await isFileExisted(newUri.substr(1));
  39. request.uri = newUri;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement