Connecting to an existing DynamoDB table

cup ip

There are many situations where you need are modernizing your app and need a more efficient way to connect to your existing datasources. GraphQL is a query language for your API that you can leverage to improve your query efficiency and your app performace. AWS AppSync is a managed GraphQL service that enables you to connect to data sources in your AWS account. In this section of the lab, you will use AWS AppSync to connect to an existing DynamoDB table in your account. You can find more information about the data used at the “Ergast API”: http://ergast.com/mrd.

1. Create a new DynamoDB table and import data

You’ll use the amplify cli to create a new DynamoDB table that hosts your race data.

amplify add storage
? Please select from one of the below mentioned services: NoSQL Database

Welcome to the NoSQL DynamoDB database wizard
This wizard asks you a series of questions to help determine how to set up your NoSQL database table.

? Please provide a friendly name for your resource that will be used to label this category in the project: raceresults
? Please provide table name: raceresults

You can now add columns to the table.

? What would you like to name this column: PK
? Please choose the data type: string
? Would you like to add another column? Yes
? What would you like to name this column: SK
? Please choose the data type: string
? Would you like to add another column? Yes
? What would you like to name this column: driverId
? Please choose the data type: string
? Would you like to add another column? Yes
? What would you like to name this column: round
? Please choose the data type: number
? Would you like to add another column? No

? Please choose partition key for the table: PK
? Do you want to add a sort key to your table? Yes
? Please choose sort key for the table: SK

? Do you want to add global secondary indexes to your table? Yes
? Please provide the GSI name: ByDriverGSI
? Please choose partition key for the GSI: driverId
? Do you want to add a sort key to your global secondary index? Yes
? Please choose sort key for the GSI: round
? Do you want to add more global secondary indexes to your table? No
? Do you want to add a Lambda Trigger for your Table? No
Successfully added resource raceresults locally

Push your changes:

amplify push --yes

Download the following script to load content in the table:

Right click on the load-script.zip link above and copy the link to this file. Depending on your browser, this could be: “Copy Link Address”, “Copy Link Location”, etc… In the graphql-real-time-race/ directory, run:

# install wget
sudo yum install wget
# copy the file locally 
wget 'path-to-loads-script.zip'
# from the graphql-real-time-race folder
unzip -o load-script.zip
rm load-script.zip

and install the aws-sdk dependency.

yarn add -D aws-sdk

Run the script (make sure to update REGION, ENV and STORAGE_RACERESULTS_NAME if necessary):

cd scripts/load/src/
REGION=us-east-2 ENV=staging STORAGE_RACERESULTS_NAME=raceresults node index 

2. Update your GraphQL Schema

When you deployed your model in the last lab with Amplify UI, it automatically created an AppSync GraphQL API to retrieve the data. Update the schema to introduce a new type Race that holds the race schedule and results for 2020.

First, add the following to the file:

amplify/backend/api/graphqlrealtimerace/schema.graphql

type Race {
  PK: String
  SK: String
  raceName: String
  round: Int
  season: String
  date: String
  time: String
  url: String
  Circuit: AWSJSON
}

type Query {
  getRaces: [Race]
}

Next, create the VTL request and response resolvers that are called when your requests are resolved.

amplify/backend/api/graphqlrealtimerace/resolvers/Query.getRaces.req.vtl

{
  "version": "2018-05-29",
  "operation": "Query",
  "query" : {
        "expression" : "#PK = :pk AND begins_with(#SK, :sk) ",
        "expressionNames" : {
            "#PK" : "PK",
            "#SK" : "SK"
        },
        "expressionValues" : {
            ":pk" : {"S": "race#2020"},
            ":sk" : {"S": "info"}
        }
    },
  "limit": 100
}

amplify/backend/api/graphqlrealtimerace/resolvers/Query.getRaces.res.vtl

#if( $ctx.error )
$util.error($ctx.error.message, $ctx.error.type, $ctx.result)
#else
$util.toJson($ctx.result.items)
#end

Finally, update the cloudformation template to create:

  • A new DynamoDB datasource that connects to your existing table
  • A new role that allows AppSync to access that table
  • a resolver with the above request and response template

Add the resources below to the Resources in the template:

amplify/backend/api/graphqlrealtimerace/stacks/CustomResources.json

[ 🌟 ] CustomResources.json

Push your changes:

amplify push --yes

3. Update your app

Update src/pages/Account.tsx to fetch and display the race information.

The new code leverages the Amplify API library. The API library provides a solution for making HTTP requests to both GraphQL as well as REST endpoints. It includes a AWS Signature Version 4 signer class which automatically signs all AWS API requests for you as well as methods to use API Keys, Amazon Cognito User Pools, or 3rd party OIDC providers.

[ 🌟 ] src/pages/Account.tsx

cup ip