Lambda Function Code

Create a Lambda function for checking ingredient availability.


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:

Press + to interact
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

...