Building a TypeScript Lambda Function for Retrieving Products
Learn how to create a Lambda function in TypeScript to retrieve a list of products from a database.
We'll cover the following...
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:
Press + to interact
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 entireProductTable
table. Again, please refer to the source code for a full listing of the ...