In the previous part, we added a lambda function to set up an endpoint to our serverless API to add a word to our DynamoDB’s words table.
Next, we would add an endpoint to our API to read words from the words table of logged in user.
Creating a ResponseUtils class
Now that our code is growing, we would like to refactor our code a little to keep it DRY. If you notice, in our lambda functions, code for sending the response for success and error cases is very similar except for the http response status code and the body, thus these two parts of code can be abstracted away in a function with status and body parameterized. So, lets first put this handling response part in a common module and then we will use it in our API functions:
📂 create a sub-folder utils
under src
📃 create a file responseUtils.ts
under src/utils
, 👇:
Adding function to read(get) Word from DynamoDB
- Create a file named
getByUser.ts
undersrc/modules/words
with below code:👇 (here is the code gist)
Add the API Endpoint function in serverless.yml
Next, lets configure the API endpoint to map to the above function we added.
In serverless.yml
, add a getLoggedUserWords
function under functions
as shown below:👇
functions:
createWord:
handler: src/modules/words/create.main
events:
- http:
path: words
method: post
cors: true
authorizer: aws_iam
getLoggedUserWords:
handler: src/modules/words/getByUser.main
events:
- http:
path: words
method: get
cors: true
authorizer: aws_iam
👆 We added a new function getLoggedUserWords
.This is similar to the previous endpoint function createWord
that we added in the previous part.
events: — http, method:get
⇒ This means the event to trigger this function is http get
. path: words
⇒ The endpoint would have the path /words
, handler: src/modules/words/getByUser.main
⇒ the request would be handled at the main
function in the getByUser.ts
file (we added above).cors: true
⇒ enable CORS as the frontend could be on a different domain.authorier: aws_iam
⇒ this means the access to the API is restricted as per the IAM permissions of the federated identity that the user has been authorized with. We will see how exactly this would work when we would set up an Identity Pool from AWS Cognito service.
Add mock data to test the service locally
From your AWS Console →DynamoDB → tables →vocabWords-dev table → Items, note down the userID
of the Item/record that we have posted to the table in the last part when testing the create-word API.
With this userId
, set the mock data, create a file named getLoggedUserWords.json
under mocks/words
with below data:👇
With the mock data ready, let’s test our lambda function:
$ serverless invoke local --function getLoggedUserWords --path mocks/words/getLoggedUserWords.json --stage dev
👏 Our GET word API using userId is working.
Deploy the service to AWS
npm run devDeploy
That’s it. Next, we would set up endpoint to get a word by its Id.
← Prev: Add(POST) lambda
┈ 🏠 ┈Next: GET by id
→