-
Notifications
You must be signed in to change notification settings - Fork 2
03 Rekognition
JP Barbosa edited this page Oct 24, 2022
·
13 revisions
code ./services/functions/process.ts
import {
S3ObjectCreatedNotificationEvent,
S3ObjectCreatedNotificationEventDetail,
SQSHandler,
} from "aws-lambda";
import { AWSError, Rekognition, S3 } from "aws-sdk";
const rekognition = new Rekognition();
const s3 = new S3();
const getLabels = async ({
bucket,
object,
}: S3ObjectCreatedNotificationEventDetail) => {
const labels = await rekognition
.detectLabels({
Image: {
S3Object: {
Bucket: bucket.name,
Name: object.key,
},
},
})
.promise();
console.log("Image has been processed", object.key);
return labels;
};
const deleteImage = async ({
bucket,
object,
}: S3ObjectCreatedNotificationEventDetail) => {
try {
await s3
.deleteObject({
Bucket: bucket.name,
Key: object.key,
})
.promise();
console.log("Image has been deleted");
} catch (error) {
console.log(error);
}
};
export const handler: SQSHandler = async (sqsEvent) => {
sqsEvent.Records.forEach(async (record) => {
const { detail }: S3ObjectCreatedNotificationEvent = JSON.parse(
record.body
);
const { key } = detail.object;
try {
const labels = await getLabels(detail);
console.log(labels);
} catch (error) {
const awsError = error as AWSError;
console.log(awsError);
} finally {
await deleteImage(detail);
}
});
};
The first start should take several minutes as many AWS resources need to be created (it has taken 10 minutes for me). Make sure to insert the correct AWS profile name according to your ~/.aws/credentials
file.
npm start
open https://console.sst.dev/sst-rekognition/YOUR_AWS_PROFILE/local
git add .
git commit -m "Rekognition"