It’s been a while since my last article Implementing Clean architecture with NestJS was rolled out where we went through some high-level concepts of clean architecture and the underlying structure of Nest.js. This article is the next part of the same series wherein I will try to break down different layers of Clean architecture and share some of the useful Nest.js tools/concepts that can be used in our implementation. Although, we will not be doing “Real” coding in this part.
So without any further delay. Let’s dive in…
Clean architecture aligns with the objective that the system should be independent of any external agency. It can be a framework, Database, or any third-party tools that are being used by the system. It also focuses on ‘Testability’ which in the modern era of development is a major consideration.
If we dissect the above diagram, what we find is
What I find really interesting and intriguing about this type of system is that it focuses on business logic instead of the frameworks and tools used to run the logic.
That means it hardly matters which database you choose, and which framework you are using. It can change and evolve over time but what will remain constant and intact is your business logic and the entities of the application.
Let’s try to slowly stack up the layers and try to understand through an example…
Basic application with Users and Products
In our example, we will represent a simple application that actually is responsible for CRUD operations on User and Product Entities.
I will be taking Nest.JS as a reference wherever I will explain the implementation of any functionality. Will touch base on concepts/tools like Dependency Injection, Repository, Class-Validator and DTO.
Entities and Use Cases: Core of our business
At its core, our business logic is defined by two layers of clean architecture:
Entities are the only independent layer in our system and will comprise information that is not meant to change over a period of time and will shape our application functionality. This also means that these layers will not be affected by any change in the external environment e.g. Services, controllers, and routing.
There will be only two entities in our application:
a) Product: ID, Name, Category, Cost & Quantity
b) User: ID, Name & Email
Use cases are only dependent on Entities and orchestrate all the scenarios that comprehend their counterpart Entity. For two of our entities, we will have the following use cases:
Product
User
Now, we need to declare these entities and use cases in our codebase and we need to have some form of database service. Database service can be an ORM/SDK which will connect with our database Postgres/MongoDB etc.
This will give us the flexibility to change the DB at our will. All we need to do is the DB implementation of the repository methods and we do not touch our logic at all.
Repository: As mentioned above, the Repository will contain the implementation of the abstract functions which will be used in our use case. In our example, those functions can be InsertItem, updateItemById, getItemById, getItems, fiterItems. This can be a generic repository. We can also have specific repositories for use cases as well which will contain more specific functions like addUser, getUserById, getUsers, addProduct. getProducts, etc.
Our use cases will always call these abstract methods without actually knowing about the DB used.
Controllers and Presenters: Data carriers for our business
Now that the core is set, we have defined our entities and use cases. Something has to act upon our use cases in order for the system to work. Data needs to be passed to the use cases to be stored and updated and similarly, processed data has to be sent out for the end users to be able to use the information. Well, That’s what Controllers and Presenters are there for.
One can think of them as adapters that bind our use cases to the outer world. In basic terminology, Controllers are used to responding to user input e.g. validation, transformation, etc. while the presenters are used to format and prepare data to be sent out.
In clean architecture, the controller’s job is:
The controller will only have the formatting of the data. No business logic. On the other hand, the job of the presenter is to get data from the application repository and then build a formatted response for the client. Its main responsibilities include
In NestJS, the functionality of the controller and presenter is implemented under controllers only, there is no different presentation component in nestjs. With the help NestJS, we will validate our user input using validation pipes and transform our DTOs to business objects using transformation pipes.
Under the hood, nestJs uses a class-validator library for all validations. All we need to do is wrap our DTO with a class-validator decorator and specify our validation properties and we are good to go.
External Interfaces: Our Frameworks
Now that our mission mangal is set to launch. All we need is the right platform. What I mean is that now we have our core ready, and gateways and channels are ready to take inputs. What we need is to set it up with the right frameworks eg. Database, logging, error handling, etc.
For example, for DB we can use TypeORM for our data services and database modelling. We can use Winston for logging. Web application frameworks can either be Express or Fastify.
Summary
This article summarizes all the layers of clean architecture using a real-world example with help of Nest.JS. We tried to demonstrate how we can build a robust structure of layer-by-layer services that decouple our core business logic from frameworks.
It gives us the superpower to change our frameworks without even worrying about breaking the code. We can easily move from MySQL to PostgreSQL, Express to Fastify without bothering our business logic. This will help us reduce the cost of transition and ease of testing.
I believe that this article would help a lot of you who strive to write clean and maintainable code. Will be back with more content soon. Till then, sayonara!
About the Author:
Junaid Bhat is currently working as a Tech Lead in Mantra Labs. He is a tech enthusiast striving to become a better engineer every day by following industry standards and aligned towards a more structured approach to problem-solving.
Let’s take a trip back in time—2008. Netflix was nothing like the media juggernaut it…
Ever wondered what life would be like if the Sun took a day off? Picture…
The Importance of Interaction Design Principles In the ever-evolving landscape of digital experiences, interaction design…
Do you think technology will advance to a point where people rely on it for…
If you think Mark Zuckerberg is just a tech genius who stumbled upon success, think…
In today’s digital landscape, where users are bombarded with options, creating a product that stands…
This website uses cookies.