How To Build Clean NodeJS REST API with AWS Lambda
Hello 👋🏼,
My name is Andrei, I am a Senior NodeJS Developer & AWS Architect Consultant / Contractor / Freelancer.
This post will guide you through designing a multi-endpoint #lambda manager using #TypeScript by implementing #AWS API Gateway (authenticated with Cognito) + AWS Lambda (for the processing layer) + AWS #DyanmoDB (for the data storage layer).
As Christmas 🎄 is just 2 months away, the application we'll build is about the Christmas market event. (tiny houses around the city with Christmas theme products).
The architecture and the application flow are already present in this article posted one week ago.
GitHub Repository: Link
Clean Lambda Repository: Link
___________________
Prerequisites:
______________________
Application Flow:
The application entry point is the handler method.
Inside this function, the event is transformed by retrieving only the needed information. (path parameters, query parameters, path, method, body) and then the #dispatcher #function is called.
2. Dispatcher
The dispatcher creates an instance of the ChristmasMarketService and the ValidatorService. A new API string variable is created based on the "${path}:${method}"
Validate method of the Validator is called.
Switch based on the API string is executed on the Endpoints enum which contains all the API combinations.
3. Validator
The validator's constructor is private, the instance is created with the getInstance method. The constructor creates an instance of AJV.
The validate method checks if the schema is already present inside the AJV instance cache
4. ChristmasMarketService
The dispatcher invokes the method of the ChristmasMarketService defined inside the #API case.
5. DynamoDBService
A completely clean microservice using NodeJS and TypeScript! 🔥
___________________
Recommended by LinkedIn
Code Structure:
2. Source Code's Directory:
- input-models.ts - this file contains the input interfaces
- response-models.ts - this file contains the response interfaces
- validator-service.ts - this file contains the logic to validate the event based on the JSON schema file
- [feature]-service.ts - this file contains the application logic (Example: CRUD operations on DynamoDB table)
- [aws-service]-wrapper - this file can be created for an AWS service where you can wrap logic to avoid duplicated code
______________________
Deployment: 🚀
We have to update the lambda implementation based on the architecture already created from the last article.
Add the following configuration to the Properties of the lambda definition:
Metadata: # Manage lambda build
BuildMethod: makefiled
You can follow the first article for the deployment step.
______________________
I hope it could help your journey into the #AWS world 😎
I have created a clean repository too as a starting development environment.
If you need any help or considerations, feel free to drop me a message. 📩
Nice to read and I hope this series will continue!