Session 6 | Node DynamoDB Workshop

Convert image

Workshop: DynamoDB, Lambda, API Gateway, and S3

In this section, we'll rewrite our Lambda functions to use the SDK to access DynamoDB data and return it to our API Gateway.


Prerequisites

Before beginning this workshop, make sure that you've completed the workshop from Session 5.

Make sure to keep the website URL for your static site handy, as you'll be testing out the update to your Lambda function through the live site.


Using DynamoDB to Pull All Table Data

  1. First, we'll need to grant the role permission to access DynamoDB. To do this, go to your IAM dashboard and select Roles:
  2. roles on iam dashboard
  3. Choose the role for your allPets Lambda function. It should look something like allPets-role-icpb4jiw.
  4. Click the blue Attach Policies button.
  5. attach policy button
  6. In the search bar, type dynamo and select the policy that says FullAccess. In real life, you would want to create a custom policy that only gives the Lambda function the limited permissions that it needs for this function, but in order to get up and running, we won't be writing a custom policy for this exercise.
  7. dynamodb access policy
  8. Click the blue Attach Policy button at the bottom. You're done adding a policy!
  9. Navigate back to your Lambda dashboard and open your allPets Lambda function.
  10. Inside of the code, we'll first require the AWS Node SDK (which gives us the ability to write code to interact with the database), then we'll create a DynamoDB client object and use that to return everything in the table with a scan operation:
  11. var aws = require('aws-sdk');
    
    exports.handler = function(event, context) {
      var dynamo = new aws.DynamoDB({region: 'us-east-1' });
      var params = { TableName : 'pets'}
    
      dynamo.scan(params, function(err, data) {
        if (err) {
          context.done(err);
        }
        else {
          context.succeed({ body: data.Items });
        }
      })
    }
  12. In your app.js file, make sure to stringify your response body:
  13. json stringify
  14. Once you've updated the code, click the orange save button, open up your index.js (or re-upload to S3 and open the static site link) and test out your All Pets button. Tada! You should see something kind of ugly appear on the page, like this: [{"id":{"N":"1"},"name":{"S":"bob"}},{"id":{"N":"2"},"name":{"S":"sarah"}}].
  15. OPTIONAL: If you're bothered by the way your data is showing up on your static page, you're welcome to change the JavaScript in app.js since this would be the frontend client's job to figure out how to parse and display the data. However, that is not the focus of this workshop, so feel free to leave it in raw form.
  16. </ol> </section>

    Inserting an Item in a DynamoDB Table

    Next, we'll update the code to create a pet in createPet.

    1. We'll need to grant the role permission to access DynamoDB. This is the same process that you did above, but for the createPet function. Make sure to do this before moving on!
    2. Then, update the code:
    3. var aws = require('aws-sdk');
      exports.handler = function(event, context) {
        var dynamo = new aws.DynamoDB({ region: 'us-east-1' });
        
        var params = {
          TableName: 'pets',
          Item: {
            'id' : {N: event['id']},
            'name' : {S: event['name']}
          }
        };
      
        dynamo.putItem(params, function(err, data) {
          if (err) {
            context.done(err);
          } else {
            context.succeed({ body: `You inserted ${event['name']} with id of ${event['id']}`});
           }
        })
      };
      

      (In actuality, you probably wouldn't return a body for an update. However, because we want to see this appear on our page, we'll return the body and our JavaScript will append that message.)

    4. Check whether your function works by clicking the button from your static site.
    5. OPTIONAL: If you're bothered by the way your data is showing up on your static page, you're welcome to change the JavaScript in app.js since this would be the frontend client's job to figure out how to parse and display the data. However, that is not the focus of this workshop, so feel free to leave it in raw form.

    Finding One Specific Item from a DynamoDB Table

    Finally, we'll change the code to find a specific pet by ID in onePet.

    1. We'll need to grant the role permission to access DynamoDB. This is the same process that you did above, but for the onePet function. Make sure to do this before moving on!
    2. Then, update the code:
    3. var aws = require('aws-sdk');
      exports.handler = function(event, context) {
        var dynamo = new aws.DynamoDB({ region: 'us-east-1' });
        var id = event.id;
        var params = {
          TableName: 'pets',
          Key: {
            "id": {
              "N": `${id}`
            },
          }
        }
        dynamo.getItem(params, function(err, data) {
          if (err) {
            context.done(err);
          }
          else {
            const pet = {
              id: data.Item.id.N,
              name: data.Item.name.S
            };
            const response = {
              body: JSON.stringify(pet),
            };
            context.succeed(response);
          }
        })
      };
    4. Check whether your function works by going to your static site, entering the ID of a pet that exists in your database, then clicking button.
    5. OPTIONAL: If you're bothered by the way your data is showing up on your static page, you're welcome to change the JavaScript in app.js since this would be the frontend client's job to figure out how to parse and display the data. However, that is not the focus of this workshop, so feel free to leave it in raw form.

    Done!

    At this point, return back to the main Session 6 page for cleanup instructions.

    </div> </div>