Astronaut loading animation Circular loading bar

Try : Insurtech, Application Development

AgriTech(1)

Augmented Reality(20)

Clean Tech(7)

Customer Journey(16)

Design(39)

Solar Industry(7)

User Experience(62)

Edtech(10)

Events(34)

HR Tech(3)

Interviews(10)

Life@mantra(11)

Logistics(5)

Strategy(17)

Testing(9)

Android(48)

Backend(32)

Dev Ops(8)

Enterprise Solution(28)

Technology Modernization(4)

Frontend(29)

iOS(43)

Javascript(15)

AI in Insurance(36)

Insurtech(63)

Product Innovation(54)

Solutions(21)

E-health(11)

HealthTech(23)

mHealth(5)

Telehealth Care(4)

Telemedicine(5)

Artificial Intelligence(139)

Bitcoin(8)

Blockchain(19)

Cognitive Computing(7)

Computer Vision(8)

Data Science(17)

FinTech(51)

Banking(7)

Intelligent Automation(27)

Machine Learning(47)

Natural Language Processing(14)

expand Menu Filters

Implementing a Clean Architecture with Nest.JS (Part 2)

7 minutes read

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

  • Layers: Each circle represents an independent layer in the system.
  • Dependency: The direction is from out to in. Basically, it means that the outer layers are dependent on the inner layer and the Entity layer is independent.
  • Entities: It will comprise all the entities that will construct your application. e.g. User Entity, Product Entity, Etc.
  • Use cases: To every entity, there are going to be specific use cases that will actually comprise all your core logic. E.g. Generating a password for the user, Adding a product, Etc.
  • Controllers/Presenters: These are basically gateways to your system. You can think of them as entry/exit points to the use cases.
  • Frameworks: It contains all the specific implementations e.g. web framework, database, loggers, Exception Handling.

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: 

  1. Entity layer: Comprises all the business entities that define our application.
  2. Use-case layer: Comprises all the business scenarios that our entities support.
  1. Entities: The building block of our application

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

  1. Use-Cases: Fundamental part of our business logic.

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

  • Add a product
  • Get a product by Id
  • Get All products
  • Get Products by cost, category, or quantity
  • Update a product
  • Delete a product

User

  • Add user
  • Get User by Id
  • Get All Users

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.

  • One way to do it is to use this SDK/ORM as a direct implementation in our use cases and hence making our use cases dependent on the SDK/ORM we use. Any change in the SDK/ORM will directly impact our logic hence defying the main motive of clean architecture.
  • Other way or I would say, the best way, is to take advantage of abstraction and dependency injection. With help of something called a repository(Abstract service/layer) which sits between our use case and the DB implementation. We can create an abstract layer of service injected into our use cases where we will define methods that will be independent of the type of database and the implementation of those methods will depend on the database used. 

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:

  • Receive the user input — some kind of DTO 
  • Sanitization: validate user input
  • Transformation: convert user inputs to the desired type required by entities/use cases
  • Last but not least, call the use case

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

  • Formatting: converting strings and dates.
  • If needed, add presentation data, like flags.
  • Prepare the data to be displayed in the UI.

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. 

Cancel

Knowledge thats worth delivered in your inbox

Platform Engineering: Accelerating Development and Deployment

The software development landscape is evolving rapidly, demanding unprecedented levels of speed, quality, and efficiency. To keep pace, organizations are turning to platform engineering. This innovative approach empowers development teams by providing a self-service platform that automates and streamlines infrastructure provisioning, deployment pipelines, and security. By bridging the gap between development and operations, platform engineering fosters standardization, and collaboration, accelerates time-to-market, and ensures the delivery of secure and high-quality software products. Let’s dive into how platform engineering can revolutionize your software delivery lifecycle.

The Rise of Platform Engineering

The rise of DevOps marked a significant shift in software development, bringing together development and operations teams for faster and more reliable deployments. As the complexity of applications and infrastructure grew, DevOps teams often found themselves overwhelmed with managing both code and infrastructure.

Platform engineering offers a solution by creating a dedicated team focused on building and maintaining a self-service platform for application development. By standardizing tools and processes, it reduces cognitive overload, improves efficiency, and accelerates time-to-market.  

Platform engineers are the architects of the developer experience. They curate a set of tools and best practices, such as Kubernetes, Jenkins, Terraform, and cloud platforms, to create a self-service environment. This empowers developers to innovate while ensuring adherence to security and compliance standards.

Role of DevOps and Cloud Engineers

Platform engineering reshapes the traditional development landscape. While platform teams focus on building and managing self-service infrastructure, application teams handle the development of software. To bridge this gap and optimize workflows, DevOps engineers become essential on both sides.

Platform and cloud engineering are distinct but complementary disciplines. Cloud engineers are the architects of cloud infrastructure, managing services, migrations, and cost optimization. On the other hand, platform engineers build upon this foundation, crafting internal developer platforms that abstract away cloud complexity.

Key Features of Platform Engineering:

Let’s dissect the core features that make platform engineering a game-changer for software development:

Abstraction and User-Friendly Platforms: 

An internal developer platform (IDP) is a one-stop shop for developers. This platform provides a user-friendly interface that abstracts away the complexities of the underlying infrastructure. Developers can focus on their core strength – building great applications – instead of wrestling with arcane tools. 

But it gets better. Platform engineering empowers teams through self-service capabilities.This not only reduces dependency on other teams but also accelerates workflows and boosts overall developer productivity.

Collaboration and Standardization

Close collaboration with application teams helps identify bottlenecks and smooth integration and fosters a trust-based environment where communication flows freely.

Standardization takes center stage here. Equipping teams with a consistent set of tools for automation, deployment, and secret management ensures consistency and security. 

Identifying the Current State

Before building a platform, it’s crucial to understand the existing technology landscape used by product teams. This involves performing a thorough audit of the tools currently in use, analyzing how teams leverage them, and identifying gaps where new solutions are needed. This ensures the platform we build addresses real-world needs effectively.

Security

Platform engineering prioritizes security by implementing mechanisms for managing secrets such as encrypted storage solutions. The platform adheres to industry best practices, including regular security audits, continuous vulnerability monitoring, and enforcing strict access controls. This relentless vigilance ensures all tools and processes are secure and compliant.

The Platform Engineer’s Toolkit For Building Better Software Delivery Pipelines

Platform engineering is all about streamlining and automating critical processes to empower your development teams. But how exactly does it achieve this? Let’s explore the essential tools that platform engineers rely on:

Building Automation Powerhouses:

Infrastructure as Code (IaC):

CI/CD Pipelines:

Tools like Jenkins and GitLab CI/CD are essential for automating testing and deployment processes, ensuring applications are built, tested, and delivered with speed and reliability.

Maintaining Observability:

Monitoring and Alerting:

Prometheus and Grafana is a powerful duo that provides comprehensive monitoring capabilities. Prometheus scrapes applications for valuable metrics, while Grafana transforms this data into easy-to-understand visualizations for troubleshooting and performance analysis.

All-in-one Monitoring Solutions:

Tools like New Relic and Datadog offer a broader feature set, including application performance monitoring (APM), log management, and real-time analytics. These platforms help teams to identify and resolve issues before they impact users proactively.

Site Reliability Tools To Ensure High Availability and Scalability:

Container Orchestration:

Kubernetes orchestrates and manages container deployments, guaranteeing high availability and seamless scaling for your applications.

Log Management and Analysis:

The ELK Stack (Elasticsearch, Logstash, Kibana) is the go-to tool for log aggregation and analysis. It provides valuable insights into system behavior and performance, allowing teams to maintain consistent and reliable operations.

Managing Infrastructure

Secret Management:

HashiCorp Vault protects secretes, centralizes, and manages sensitive data like passwords and API keys, ensuring security and compliance within your infrastructure.

Cloud Resource Management:

Tools like AWS CloudFormation and Azure Resource Manager streamline cloud deployments. They automate the creation and management of cloud resources, keeping your infrastructure scalable, secure, and easy to manage. These tools collectively ensure that platform engineering can handle automation scripts, monitor applications, maintain site reliability, and manage infrastructure smoothly.

The Future is AI-Powered:

The platform engineering landscape is constantly evolving, and AI is rapidly transforming how we build and manage software delivery pipelines. The tools like Terraform, Kubecost, Jenkins X, and New Relic AI facilitate AI capabilities like:

  • Enhance security
  • Predict infrastructure requirements
  • Optimize resource security 
  • Predictive maintenance
  • Optimize monitoring process and cost

Conclusion

Platform engineering is becoming the cornerstone of modern software development. Gartner estimates that by 2026, 80% of development companies will have internal platform services and teams to improve development efficiency. This surge underscores the critical role platform engineering plays in accelerating software delivery and gaining a competitive edge.

With a strong foundation in platform engineering, organizations can achieve greater agility, scalability, and efficiency in the ever-changing software landscape. Are you ready to embark on your platform engineering journey?

Building a robust platform requires careful planning, collaboration, and a deep understanding of your team’s needs. At Mantra Labs, we can help you accelerate your software delivery. Connect with us to know more. 

Cancel

Knowledge thats worth delivered in your inbox

Loading More Posts ...
Go Top
ml floating chatbot