Skip to content

Instantly share code, notes, and snippets.

@pgriess
Last active July 8, 2019 18:27
Show Gist options
  • Save pgriess/8835636c0a8ad544d33a096584eab9f1 to your computer and use it in GitHub Desktop.
Save pgriess/8835636c0a8ad544d33a096584eab9f1 to your computer and use it in GitHub Desktop.
AcceptContentNegotiation
'use strict';
const {
ValueTuple,
awsPerformEncodingNegotiation,
awsPerformTypeNegotiation } = require('http_content_negotiation');
const SERVER_ENCODINGS = [
new ValueTuple('br', new Map([['q', 1]])),
new ValueTuple('gzip', new Map([['q', 0.9]])),
new ValueTuple('identity', new Map([['q', 0.1]]))];
const SERVER_IMAGE_TYPES = [
new ValueTuple('image/webp', new Map([['q', 1]])),
new ValueTuple('image/jpeg', new Map([['q', 0.5]]))];
const SERVER_IMAGE_WHITELIST = new Set([
'image/jpeg',
]);
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
if (request.uri.endsWith('.jpg')) {
const type = awsPerformTypeNegotiation(
request.headers, SERVER_IMAGE_TYPES, SERVER_IMAGE_WHITELIST);
if (type) {
const uriWithoutExtension = request.uri.slice(0, -3);
switch (type.value) {
case 'image/webp':
request.uri = uriWithoutExtension + 'webp';
break;
case 'image/jpeg':
// Nothing to do
break;
}
}
} else if (!request.uri.startsWith('/gzip/') &&
!request.uri.startsWith('/br/')) {
const encoding = awsPerformEncodingNegotiation(request.headers, SERVER_ENCODINGS);
if (encoding && encoding.value !== 'identity') {
request.uri = '/' + encoding.value + request.uri;
}
}
callback(null, request);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment