Skip to content

Instantly share code, notes, and snippets.

@SahanAmarsha
Last active November 7, 2023 20:53
Show Gist options
  • Save SahanAmarsha/a6d62b0ae6891e6d474ec4f22e31e9ad to your computer and use it in GitHub Desktop.
Save SahanAmarsha/a6d62b0ae6891e6d474ec4f22e31e9ad to your computer and use it in GitHub Desktop.
SahanAmarsha/lambda-image-resizer/index.js
const aws = require("aws-sdk");
const sharp = require("sharp");
const s3 = new aws.S3();
exports.handler = async function (event, context) {
console.log("Received S3 event:", JSON.stringify(event, null, 2));
if (event.Records[0].eventName === "ObjectRemoved:Delete") {
return;
}
const bucket = event.Records[0].s3.bucket.name;
const key = event.Records[0].s3.object.key;
console.log(`Bucket: ${bucket}`, `Key: ${key}`);
try {
// get image from s3
let image = await s3.getObject({ Bucket: bucket, Key: key }).promise();
// resize image
image = await sharp(image.Body);
const metadata = await image.metadata();
if (metadata.width > 900) {
const resizedImage = await image
.resize({ width: 900 })
.withMetadata()
.toBuffer();
// store image
console.log("RESIZED IMAGE");
await s3
.putObject({ Bucket: bucket, Key: key, Body: resizedImage })
.promise();
return "RESIZED IMAGE";
} else {
console.log("NOT RESIZED IMAGE");
return "NOT RESIZED IMAGE";
}
} catch (err) {
context.fail(`Error resizing image: ${err}`);
}
};
@amonger
Copy link

amonger commented Nov 7, 2023

If this was called by a trigger - wouldn't the put object call to the same bucket end up invoking the trigger again? Infinite loop?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment