Now let’s create an API that allows a user to update a note with a new note object given the id.

Add the Function

Change indicator Create a new file in packages/functions/src/update.ts and paste the following.

import { Resource } from "sst";
import { Util } from "@notes/core/util";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { UpdateCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

const dynamoDb = DynamoDBDocumentClient.from(new DynamoDBClient({}));

export const main = Util.handler(async (event) => {
  const data = JSON.parse(event.body || "{}");

  const params = {
    TableName: Resource.Notes.name,
    Key: {
      // The attributes of the item to be created
      userId: "123", // The id of the author
      noteId: event?.pathParameters?.id, // The id of the note from the path
    },
    // 'UpdateExpression' defines the attributes to be updated
    // 'ExpressionAttributeValues' defines the value in the update expression
    UpdateExpression: "SET content = :content, attachment = :attachment",
    ExpressionAttributeValues: {
      ":attachment": data.attachment || null,
      ":content": data.content || null,
    },
  };

  await dynamoDb.send(new UpdateCommand(params));

  return JSON.stringify({ status: true });
});

This should look similar to the create.ts function combined. Here we make an update DynamoDB call with the new content and attachment values in the params.

Add the Route

Let’s add a new route for the get note API.

Change indicator Add the following below the GET /notes/{id} route in infra/api.ts.

api.route("PUT /notes/{id}", "packages/functions/src/update.main");

Deploy Our Changes

If you switch over to your terminal, you will notice that your changes are being deployed.

You should see that the new API has been deployed.

+  Complete
   Api: https://5bv7x0iuga.execute-api.us-east-1.amazonaws.com

Test the API

Now we are ready to test the new API. In an earlier chapter we tested our create note API. It should’ve returned the new note’s id as the noteId.

Change indicator Run the following in your terminal.

$ curl -X PUT \
-H 'Content-Type: application/json' \
-d '{"content":"New World","attachment":"new.jpg"}' \
https://5bv7x0iuga.execute-api.us-east-1.amazonaws.com/notes/<NOTE_ID>

Make sure to replace the id at the end of the URL with the noteId from before.

Here we are making a PUT request to a note that we want to update. We are passing in the new content and attachment as a JSON string.

The response should look something like this.

{"status":true}

Next we are going to add the API to delete a note given its id.