S3 Invoke Lambda Function to DynamoDB

Expanding on the SAM template examples starting with SQS I've added a very simple S3 trigger example that updates a DynamoDB table with the object name when a new object is added to the bucket.

S3/Lambda -> DynamoDB

The SAM template is as follows:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyS3TriggerFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: index.handler
      Runtime: nodejs14.x
      Timeout: 30
      Environment:
        Variables:
          DB_NAME: !Ref MyS3TriggerFunctionDynamoDB
      Policies: 
        - AWSLambdaExecute
        - AmazonDynamoDBFullAccess
      Events:
        MyS3TriggerFunctionEvent:
          Type: S3
          Properties:
            Bucket: !Ref MyS3TriggerFunctionBucket
            Events: s3:ObjectCreated:*
  MyS3TriggerFunctionBucket:
    Type: AWS::S3::Bucket
  MyS3TriggerFunctionDynamoDB:
    Type: AWS::Serverless::SimpleTable
    Properties:
      TableName: MyS3TriggerFunctionDynamoDB
      PrimaryKey:
        Name: id
        Type: String
      ProvisionedThroughput:
        ReadCapacityUnits: 1
        WriteCapacityUnits: 1

This template creates an S3 event type as defined here:

      Events:
        MyS3TriggerFunctionEvent:
          Type: S3
          Properties:
            Bucket: !Ref MyS3TriggerFunctionBucket
            Events: s3:ObjectCreated:*

The Lambda function code is below:

const aws = require('aws-sdk')
const uuid = require('uuid')

const DynamoDB = new aws.DynamoDB.DocumentClient({ region: "us-east-1" })

exports.handler = async (event) => {
    const key = event.Records[0].s3.object.key

    let params = {
        TableName: process.env.DB_NAME,
        Item: {
            id: uuid.v4(),
            image: key,
        }
    }    

    try {
        await DynamoDB.put(params).promise()
        console.log({"success": true, "msg": params})
    } catch (err) {
        console.log({"success": false, "msg": err.message})
    }
}

To create the AWS resources using the template run sam build. Once that completes run sam deploy --guided.