Sitemap
Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Asynchronous API with DynamoDB Streams

5 min readMay 13, 2021

--

What is DynamoDB Streams

Lambda Function

const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
const TABLE_NAME = "Restaurant";
const TTL = 300;
exports.handler = async(event) => {
var plist = [];
event.Records.forEach(record => {
if (record.eventName == "INSERT") {
plist.push(processInsert(record.dynamodb.NewImage));
}
});
await Promise.all(plist);
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
const processInsert = async(newImage) => {
// Business Logic to process the input
console.log("Processing: " + JSON.stringify(newImage));
var error = await businesslogic(newImage);
if (!error) {
await ddb.update({
TableName: TABLE_NAME,
Key: { id: newImage.id.S },
UpdateExpression: "set #error = :error",
ExpressionAttributeValues: { ":error": error },
ExpressionAttributeNames: { "#error": "error" }
}).promise();
}
else {
await ddb.update({
TableName: TABLE_NAME,
Key: { id: newImage.id.S },
UpdateExpression: "set #ttl = :ttl",
ExpressionAttributeValues: { ":ttl": TTL + Math.floor(Date.now() / 1000) },
ExpressionAttributeNames: { "#ttl": "ttl" }
}).promise();
}
};
const businesslogic = async(input) => {
return; // return "Error Details" in case of any error
};

IAM Role for Lambda

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"dynamodb:DescribeStream",
"dynamodb:UpdateItem",
"dynamodb:GetShardIterator",
"dynamodb:GetItem",
"dynamodb:UpdateTable",
"dynamodb:GetRecords"
],
"Resource": [
"arn:aws:dynamodb:us-east-1:1234567890:table/TableName",
"arn:aws:dynamodb:us-east-1:1234567890:table/TableName/index/*",
"arn:aws:dynamodb:us-east-1:1234567890:table/TableName/stream/*"
]
}
]
}

DynamoDB Table

API Gateway

{
"TableName":"TableName",
"Item": {
"id": {"S": "$context.requestId"},
"request": {"S": "$util.escapeJavaScript($input.body)"}
}
}

Benefits

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

No responses yet