Count likes using DynamoDb Streams

Count likes using DynamoDb Streams

the lambda handler is configured to trigger on DynamoDb Stream updates with a filter configured that do match the records with id that starts with item-

import json
import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('posts')

def updateCounter(key, count):
    parts = key.split('-')
    countKey = "likes-" + parts[1]
    response = table.get_item(
        Key={
            'id':  countKey
        })
    if "Item" in response:
        currentCount = response["Item"]["contor"]
        table.update_item(
            Key={
                'id':  countKey
            },
            UpdateExpression='SET contor = :nextCount',
            ExpressionAttributeValues={
                ':nextCount': currentCount + count,
                ':currentCount': currentCount
            },
            ConditionExpression="contor = :currentCount"
        )
    else:
        table.put_item(
            Item={
                'id':  countKey,
                'contor': count
            },
        )

def lambda_handler(event, context):
    for record in event['Records']:
        key = record["dynamodb"]["Keys"]["id"]["S"]
        # if key.startswith("like-"):
        print(record['eventID'])
        if record['eventName'] == 'INSERT':
            updateCounter(key, 1)
        elif record['eventName'] == 'REMOVE':
            updateCounter(key, -1)
        print(record['eventName'])
        print(record)
    print('Successfully processed %s record(s).' % str(len(event['Records'])))
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Related Posts