I am working on a feature where the incoming requests from CloudFront are intercepted using Lambda Edge and then the program checks if there is a jpg file of same name present in S3. If yes, it updates the request to use jpg file otherwise use png file.
In the logs, I see a request coming in and the request getting updated with the jpg url in case a jpg file exists. But, on the webpage I still png file in every case.
Can anybody please advise what I am doing wrong?
Here's the code:
exports.handler = async (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const origin = request.origin;
console.log("Original Request: " + request.uri);
if(request.uri.startsWith('/looks/') && request.uri.endsWith('.png')) {
var jpg_file = request.uri.replace(".png", ".jpg");
console.log("Modified Request: "+ jpg_file);
var jpgFileExists = checkIfFileExists(s3, jpg_file.substr(1));
jpgFileExists.then(function(result) {
const type = result;
console.log("TYPE: " + type);
if(type) {
console.log("send JPG file");
request.uri = jpg_file;
} else {
console.log("send png file");
//do nothing
}
});
}
console.log("FINAL URL: " + request.uri);
return callback(null, request);
};
async function checkIfFileExists(s3, fileName) {
let exist = true;
let params = {
Bucket: "bucketName",
Key: fileName
};
try {
console.log("Checking for file: " + fileName);
await s3.headObject(params).promise();
} catch (err) {
exist = false;
}
console.log("EXISTS: " + exist);
return exist;
}