I was able to get my Lambda function working! This is my current code:
import json
import os
import boto3
dynamo = boto3.resource("dynamodb")
TABLE_NAME = os.environ.get("TABLE_NAME", "nathanferguson-visitorcounter")
ITEM_KEY = {"id": "1"} # keep this here if id is always "1"
def lambda_handler(event, context):
table = dynamo.Table(TABLE_NAME)
try:
# Atomic increment (single call)
resp = table.update_item(
Key=ITEM_KEY,
UpdateExpression="SET visitorCount = if_not_exists(visitorCount, :zero) + :inc",
ExpressionAttributeValues={":zero": 0, ":inc": 1},
ReturnValues="UPDATED_NEW"
)
new_count = int(resp["Attributes"]["visitorCount"])
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET",
"Access-Control-Allow-Headers": "Content-Type",
"Content-Type": "application/json"
},
"body": json.dumps({"count": new_count})
}
except Exception as e:
# log for CloudWatch
print("Error updating visitor count:", str(e))
return {
"statusCode": 500,
"headers": {"Access-Control-Allow-Origin": "*", "Content-Type": "application/json"},
"body": json.dumps({"error": "Internal Server Error", "message": str(e)})
}
From this code, it's able to interact with my DynamoDb table to increment the current value by 1. In order to more easily invoke this function, I added an API gateway to the function. So now I can access it by using that URL, pretty cool!
Issues
- Returning the correct number
- When I returned the count from the function initially, it was just a plain number. This was causing issues down the line of not being able to read that number and display it in the visitor count section of my page. So I updated it to return as JSON which I was able to use more easily in the HTML page
I also ended up creating a very simple test for the function within the AWS console, basically by just putting "{}", since the function just needed to run.
Coming up next
I need to figure out how to call that counter on page load, as well as displaying it within the site itself. Onward!
Top comments (0)