sam-rest-test
Testing a RESTful CRUD API backed by DynamoDB managed via SAM.
Structure
api
contains the lambda functions that run in AWS API Gatewayapp
contains the frontend react apptemplate.yaml
contains the sam template for the project structure in AWS
Setup
- Install node 12, docker, jq, sam-cli (yeah, asks for homebrew), aws cli, and optionally the VSCode plugin
- Run
npm install
in the package root, and insideapi
andapp
- Run
npm run build
(ornpm run watch
) at the project root to build theapi
(output should be inapi/build
)
Deploying to AWS
- Run
sam deploy --guided
to deploy to AWS (please remember to use the AWS development account), you'll need to re-run this every time you modify your lambda code or the content of the template - Run
npm run dev:create-user
to create a usersample@example.com
with passwordpassword
in the user pool - Run
npm run dev:export-stack
to write a localapp/src/aws.json
file with the IDs of the resources created in AWS that will be used by the react app
Running the app
- Run
npm run start
in theapp
folder - Note that the REGION in the
app
is hardcoded tous-east-1
, change it inapp/src/index.ts
if needed
Running locally
- Run
npm run dev:start-db
to start a docker container with a local dynamodb - Run
npm run dev:create-tables
to create local tables using the schema inscripts/create-tables.sh
(ideally, this schema should be loaded from thetemplate.yaml
instead) - Run
npm run dev:start-api
to start a local version of the API gateway usingsam
- Run the app pointing to the local api with
npm run start-local
in theapp
folder
You can also try out the following requests:
# Create a relayer
curl -XPOST 'http://localhost:4000/relayers' -d '{ "relayerId": "1", "tenantId": "DEFAULT_TENANT", "name": "relayer1" }' -H "Content-Type: application/json"
# Get the relayer created
curl 'http://localhost:4000/relayers/1'
# List all relayers
curl 'http://localhost:4000/relayers'
Also, note that the react-app will try to connect to the cognito user pool for auth. This means you need to deploy to AWS before running the app locally. If you want to skip this and run everything locally, remove the authorization custom_header
from app/src/index.ts
, and the call to withAuthenticator
in app/src/App.ts
.
Next steps
- Find out a better way to define env variables for local testing, that don't require adding the name of each function in
api/envs/dev.json
- Split the
template.yaml
into several templates, in order to separate the resources updated frequently (eg lambdas) and the more permanent resources (eg cognito) - Use a custom lambda authorizer to load the tenant info, and wrap the Dynamo client in an IAM role restricted to the current tenant (see this article)
- Setup unit tests for lambdas using jest-dynamodb or jest-dynalite
- Set up a CI/CD using CircleCI or Github actions
- Set up a deployment step to S3 for the built react-app
- Try out local lambda debugging