Lädt...


🔧 Implementing Clean Architecture with TypeScript


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Clean Architecture is a software design philosophy that aims to create systems that are easy to maintain, test, and understand. It emphasizes the separation of concerns, making sure that each part of the system has a single responsibility. In this article, we'll explore how to implement Clean Architecture using TypeScript.

Table of Contents

  1. Introduction to Clean Architecture
  2. Core Principles
  3. Setting Up the Project
  4. Folder Structure
  5. Entities
  6. Use Cases
  7. Interfaces
  8. Frameworks and Drivers
  9. Putting It All Together
  10. Conclusion

Introduction to Clean Architecture

Clean Architecture, introduced by Robert C. Martin (Uncle Bob), provides a clear separation between the different parts of a software system. The main idea is to keep the core business logic independent of external factors such as databases, UI, or frameworks.

Core Principles

  1. Independence: The business logic should be independent of UI, database, or external systems.
  2. Testability: The system should be easy to test.
  3. Separation of Concerns: Different parts of the system should have distinct responsibilities.
  4. Maintainability: The system should be easy to maintain and evolve.

Setting Up the Project

First, let's set up a TypeScript project. You can use npm or yarn to initialize a new project.

mkdir clean-architecture-ts
cd clean-architecture-ts
npm init -y
npm install typescript ts-node @types/node --save-dev

Create a tsconfig.json file to configure TypeScript.

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  }
}

Folder Structure

A clean architecture project typically has the following folder structure:

src/
├── entities/
├── usecases/
├── interfaces/
├── frameworks/
└── main.ts

Entities

Entities represent the core business logic. They are the most important part of the system and should be independent of external factors.

// src/entities/user.entity.ts
export class User {
    constructor(id: string, public email: string, public password:string) {}

    static create(email: string, password: string) {
        const userId = uuid()
        return new User(userId, email, password)
    }
}

Use Cases

Use cases contain the application-specific business rules. They orchestrate the interaction between entities and interfaces.

// src/usecases/create-user.usecase.ts
import { User } from "../entities/user.entity";
import { UsersRepository } from "../interfaces/users.repository"

interface CreateUserRequest {
  email: string;
  password: string;
}

export class CreateUserUseCase {
  constructor(private userRepository: UserRepository) {}

  async execute(request: CreateUserRequest): Promise<void> {
    const user = User.create(request.email, request.password)
    await this.userRepository.save(user);
  }
}

Interfaces

Interfaces are the contracts between the use cases and the outside world. They can include repositories, services, or any external system.

// src/interfaces/users.repository.ts
import { User } from "../entities/user.entity";

export interface UserRepository {
  save(user: User): Promise<void>;
}

Frameworks and Drivers

Frameworks and drivers contain the implementation details of the interfaces. They interact with external systems like databases or APIs.

// src/frameworks/in-memory-users.repository.ts
import { User } from "../entities/User";
import { UserRepository } from "../interfaces/users.repository";

export class InMemoryUsersRepository implements UserRepository {
  private users: User[] = [];

  async save(user: User): Promise<void> {
    this.users.push(user);
  }
}

Putting It All Together

Finally, let's create an entry point to wire everything together.

// src/main.ts
import { CreateUser } from "./usecases/create-user.usecase";
import { InMemoryUserRepository } from "./frameworks/in-memory-users.repository";

const userRepository = new InMemoryUserRepository();
const createUser = new CreateUserUseCase(userRepository);

createUser.execute({ email: "[email protected]", password: "123456" })
  .then(() => console.log("User created successfully"))
  .catch(err => console.error("Failed to create user", err));

Compile and run the project:

tsc
node dist/main.js

Conclusion

By following the principles of Clean Architecture, we can create a system that is maintainable, testable, and adaptable to change. TypeScript provides strong typing and modern JavaScript features that help enforce these principles. With a clear separation of concerns, our codebase becomes easier to understand and evolve over time.

Feel free to expand or modify this article as needed!

...

🔧 Implementing Clean Architecture with TypeScript


📈 43.08 Punkte
🔧 Programmierung

🔧 Comparing All-in-One Architecture, Layered Architecture, and Clean Architecture


📈 41.05 Punkte
🔧 Programmierung

🔧 Implementing Clean Architecture in Flutter: A Guide for Scalable App Development


📈 32.95 Punkte
🔧 Programmierung

🔧 Implementing Clean Architecture and Adding a Caching Layer


📈 32.95 Punkte
🔧 Programmierung

🔧 Implementing Persistence With Clean Architecture


📈 32.95 Punkte
🔧 Programmierung

🔧 Clean Architecture: Keeping Code Clean and Maintainable


📈 32.19 Punkte
🔧 Programmierung

🔧 The difference between clean code and clean architecture?


📈 32.19 Punkte
🔧 Programmierung

🔧 Implementando Clean Architecture com TypeScript


📈 31.21 Punkte
🔧 Programmierung

🔧 Modern API Development with Node.js, Express, and TypeScript using Clean Architecture


📈 31.21 Punkte
🔧 Programmierung

🔧 Clean Architecture in Node.js: An Approach with TypeScript and Dependency Injection.


📈 31.21 Punkte
🔧 Programmierung

🔧 The Art of Writing Clean Functions: Clean Code Practices


📈 22.21 Punkte
🔧 Programmierung

🔧 The Clean Code book and the clean code paradigms


📈 22.21 Punkte
🔧 Programmierung

🔧 🧹 It's Time to Spring Clean Your Codebase: Celebrate National Clean Out Your Computer Day! 🖥️ ✨


📈 22.21 Punkte
🔧 Programmierung

🔧 Excel Tutorial – How to Clean Data with the TRIM() and CLEAN() Functions


📈 22.21 Punkte
🔧 Programmierung

🔧 Implementing a Custom Dropdown Component in React with TypeScript and Floating-UI


📈 22 Punkte
🔧 Programmierung

🔧 Implementing Golang's chan in TypeScript with @harnyk/chan


📈 22 Punkte
🔧 Programmierung

🔧 Mastering TypeScript: Implementing Push, Pop, Shift, and Unshift in Tuples


📈 22 Punkte
🔧 Programmierung

🔧 Implementing React `forwardRef` with TypeScript


📈 22 Punkte
🔧 Programmierung

🔧 Understanding and Implementing Type Guards in TypeScript


📈 22 Punkte
🔧 Programmierung

🔧 Implementing Passport Local With Yarn, Typescript, Express and PostgreSQL


📈 22 Punkte
🔧 Programmierung

🔧 Understanding and Implementing Advanced Encryption Standard (AES) in Node.js with TypeScript


📈 22 Punkte
🔧 Programmierung

🔧 Implementing the Pipe Operator in TypeScript


📈 22 Punkte
🔧 Programmierung

🕵️ Implementing a New CPU Architecture for Ghidra


📈 21.85 Punkte
🕵️ Reverse Engineering

🔧 Implementing a Message-Driven Architecture for Live IPL Scores in a Chrome Extension


📈 21.85 Punkte
🔧 Programmierung

🔧 Implementing Event-Driven Architecture in .NET Core Microservices with RabbitMQ


📈 21.85 Punkte
🔧 Programmierung

🔧 Implementing Event-Driven Architecture in Rails with Active Support Instrumentation


📈 21.85 Punkte
🔧 Programmierung

🔧 Implementing MVVM Architecture in iOS with Combine.


📈 21.85 Punkte
🔧 Programmierung

🔧 Implementing and Deploying a Real-Time AI-Powered Chatbot With Serverless Architecture


📈 21.85 Punkte
🔧 Programmierung

🔧 Implementing a Secure and Scalable Microservices Architecture


📈 21.85 Punkte
🔧 Programmierung

🔧 Implementing a Service Oriented Architecture in 2024


📈 21.85 Punkte
🔧 Programmierung

🔧 Enhancing Resiliency: Implementing the Circuit Breaker Pattern for Strong Serverless Architecture on AWS


📈 21.85 Punkte
🔧 Programmierung

🔧 The Benefits of Implementing Serverless Architecture in Your CI/CD Pipeline


📈 21.85 Punkte
🔧 Programmierung

📰 Data Mesh: Concepts and best practices for implementing a Product-centric Data Architecture


📈 21.85 Punkte
🔧 AI Nachrichten

matomo