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/.

Follow publication

Asynchronous API with DynamoDB Streams

Vikas K Solegaonkar
Nerd For Tech
Published in
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

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

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

Write a response