Search⌘ K
AI Features

Building a TypeScript Lambda Function for Retrieving Products

Explore how to create a TypeScript Lambda function for an AWS serverless API that retrieves a list of products from DynamoDB. Learn to structure the function, query the database, and format JSON responses to fetch product data securely and efficiently.

Let’s now turn our attention to the Lambda function that returns our list of products, which is a GET handler at the endpoint /products. This handler will need to query or scan our ProductTable and generate a JSON response, which is an array of each product found in the database.

Lambda function structure and querying the database

Our Lambda function, in the file named products.ts, is as follows:

TypeScript 4.9.5
export const getHandler = async (
event: APIGatewayProxyEvent,
context: Context
) => {
let response = {};
try {
let scanResults =
await executeScan(
dynamoDbClient,
getProductScanParameters()
);
let outputArray = [];
if (scanResults?.Items) {
for (let item of scanResults.Items) {
outputArray.push(getProduct(item));
}
}
response = {
'statusCode': 200,
'body': JSON.stringify(outputArray)
}
} catch (err) {
console.log(err);
return err;
}
return response;
};

Here, we have the standard structure for a Lambda function.

  • Our function starts by creating a variable named scanResults on line 7, which will hold the results of querying the entire ProductTable table. Again, please refer to the source code for a full listing of the ...