Search⌘ K
AI Features

Lambda Function Code

Explore how to develop a Lambda function that verifies ingredient availability by querying DynamoDB, updates inventory for sufficient ingredients, and returns appropriate success or failure responses. Understand the code structure, database interactions, and error handling within AWS serverless workflows.


In the previous lesson, we created a configuration code for Lambda as well as all needed permissions. Now, we can focus on the actual code.

Check ingredient availability

Let's start the coding part. Below, we can see our project:

Project


Let's open a file named ingredientPreparation.ts from the handlers folder and add the following code:

TypeScript 4.9.5
import { DynamoDB } from 'aws-sdk';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
const dynamoDB = new DynamoDB.DocumentClient();
const tableName = process.env.INVENTORY_TABLE;
interface Ingredient {
ingredient: string;
quantity: number;
}
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const requiredIngredients: Ingredient[] = JSON.parse(event.body).requiredIngredients;
const ingredientAvailabilityPromises = requiredIngredients.map(async (ingredient) => {
const result = await dynamoDB
.get({
TableName: tableName,
Key: { ingredient: ingredient.ingredient },
})
.promise();
return {
ingredient: ingredient.ingredient,
requiredQuantity: ingredient.quantity,
availableQuantity: result.Item ? result.Item.quantity : 0,
};
});
const ingredientAvailability = await Promise.all(ingredientAvailabilityPromises);
};

First, we'll check if the required ingredients are available in the inventory. We'll iterate through the requiredIngredients list and get each ingredient's availability from the DynamoDB table.

Process the ingredient availability data

...