Now we are going to add an API that returns a list of all the notes a user has. This’ll be very similar to the previous chapter where we were returning a single note.

Add the Function

Create a new file in services/functions/list.js with the following.

import handler from "../util/handler";
import dynamoDb from "../util/dynamodb";

export const main = handler(async () => {
  const params = {
    TableName: process.env.TABLE_NAME,
    // 'KeyConditionExpression' defines the condition for the query
    // - 'userId = :userId': only return items with matching 'userId'
    //   partition key
    KeyConditionExpression: "userId = :userId",
    // 'ExpressionAttributeValues' defines the value in the condition
    // - ':userId': defines 'userId' to be the id of the author
    ExpressionAttributeValues: {
      ":userId": "123",
    },
  };

  const result = await dynamoDb.query(params);

  // Return the matching list of items in response body
  return result.Items;
});

This is pretty much the same as our get.js except we use a condition to only return the items that have the same userId as the one we are passing in. In our case, it’s still hardcoded to 123.

Add the Route

Let’s add the route for this new endpoint.

Add the following above the POST /notes route in stacks/ApiStack.js.

"GET /notes": "functions/list.main",

Deploy Our Changes

If you switch over to your terminal, you’ll notice that you are being prompted to redeploy your changes. Go ahead and hit ENTER.

Note that, you’ll need to have sst start running for this to happen. If you had previously stopped it, then running npx sst start will deploy your changes again.

You should see that the API stack is being updated.

Stack dev-notes-ApiStack
  Status: deployed
  Outputs:
    ApiEndpoint: https://5bv7x0iuga.execute-api.us-east-1.amazonaws.com

Test the API

Let’s test the list all notes API. Head to the API tab of the SST Console.

Select the /notes API and click Send.

You should see the notes being returned in the response.

SST Console list notes API request

Note that, we are getting an array of notes. Instead of a single note.

Next we are going to add an API to update a note.