A Lambda function lets you run code automatically when something happens. Using it with DynamoDB helps you save or get data without managing servers.
0
0
Lambda function with DynamoDB
Introduction
You want to save user info automatically when they sign up.
You need to update inventory counts when a sale happens.
You want to fetch data from DynamoDB when a website visitor requests it.
You want to process data changes in DynamoDB and react to them.
You want to run small tasks triggered by events without running a full server.
Syntax
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'YourTableName', Key: { id: event.id } }; try { const data = await dynamo.get(params).promise(); return data.Item; } catch (error) { return { error: error.message }; } };
This is a simple Lambda function in Node.js that reads an item from DynamoDB.
Replace 'YourTableName' and 'id' with your actual table and key names.
Examples
This example saves a new user to the 'Users' table using data from the event.
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'Users', Item: { id: event.id, name: event.name } }; await dynamo.put(params).promise(); return { message: 'User saved' }; };
This example fetches a user by id from the 'Users' table and returns it.
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'Users', Key: { id: event.id } }; const data = await dynamo.get(params).promise(); return data.Item || { message: 'User not found' }; };
Sample Program
This Lambda function saves a product to the 'Products' table and then retrieves it to confirm it was saved.
DynamoDB
exports.handler = async (event) => { const AWS = require('aws-sdk'); const dynamo = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'Products', Item: { id: '101', name: 'Coffee Mug', price: 12.99 } }; try { await dynamo.put(params).promise(); const getParams = { TableName: 'Products', Key: { id: '101' } }; const data = await dynamo.get(getParams).promise(); return data.Item; } catch (error) { return { error: error.message }; } };
OutputSuccess
Important Notes
Make sure your Lambda has permission to access DynamoDB.
Use AWS SDK's DocumentClient for easier JSON handling.
Always handle errors to avoid crashes.
Summary
Lambda functions let you run code triggered by events without servers.
Use AWS SDK's DocumentClient to read and write DynamoDB data easily.
Remember to set correct permissions and handle errors in your code.