Table of Contents
Clean Architecture
Project function:
Project structure
Finally
Home Web Front-end JS Tutorial What is Clean Architecture? How to implement it with Node?

What is Clean Architecture? How to implement it with Node?

Feb 22, 2023 pm 07:39 PM
javascript node.js Architecture

What is Clean Architecture? This article will take you through Clean Architecture and talk about how to implement Clean Architecture using Node.js. I hope it will be helpful to you!

What is Clean Architecture? How to implement it with Node?

Clean Architecture

Clean Architecture is a software architecture pattern proposed by Robert C. Martin to divide the system into layer to achieve separation of concerns, making the system easier to understand, maintain and expand. This architecture divides the system into four levels, from inside to outside: entity layer, use case layer, presentation layer, infrastructure (repository, framework, etc.).

What is Clean Architecture? How to implement it with Node?

In this article, we will introduce how to implement Clean Architecture using Node.js and provide some sample code to demonstrate the key concepts of the architecture.

Next we will use the TypeScript project example (github.com/lulusir/cle…). The project uses a Monorepo structure and is managed using Rush.js. The server folder contains three sub-projects, namely core, koa and nestjs-app. Core is the core business logic, koa uses koa prisma as the underlying framework web project, and nestjs-app uses nestjs typeorm as the underlying framework. s project. The purpose is to demonstrate how the same business logic can bridge different frameworks. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]

In this project, the entity layer contains entity objects and related business rules and logic, and the use case layer Contains the use cases and business logic of the system, the repository layer is responsible for saving and retrieving data, and the presentation layer is the http interface exposed to the outside.

Project function:

Realize a post publishing and browsing function

  • User creation and query

  • Publish, edit, query, delete posts

Project structure

├── server
│   ├── core // 核心业务逻辑
│   │   └── src
│   │       ├── domain
│   │       ├── repository
│   │       └── useCase
│   ├── koa
│   │   └── src
│   │       ├── post
│   │       └── user
│   └── nestjs-app
│       ├── src
│           ├── post
│           │   ├── dto
│           │   └── entities
│           └── user
│               └── entities
└── web
Copy after login
  • core: core is the code of the core business logic

    • Domain: stores entity-related code, such as business-specific models, etc.
    • Use Cases: stores business logic-related code Code, such as processing business logic, data validation, calling Repository, etc.
    • Repository: Storage and related interfaces for external storage systems
  • ##koa/nestjs-app: The actual consumer of core

      Implements the specific Router and Repository based on the interface of core
##Project features

Use the ideas of DDD and Clean Architecture to separate business logic from framework implementation.
  • Use the monorepo project structure to facilitate the management of multiple related projects.
  • Provides multiple sample applications to make it easy to get started quickly.
  • Based on TypeScript, improving code readability and maintainability.
  • In core, we have the core business logic code. This level contains domains, repository interfaces, and use cases. Domains contain code related to entities, such as a specific business model. The repository contains relevant interfaces to external storage systems. Use cases contain code related to business logic, such as handling business logic, data validation, and calling repositories.

At the koa/nestjs-app level, we have actual consumers at the core level. They implement specific routers and repositories based on the interfaces provided by the core layer. One of the main advantages of using Clean Architecture is that it separates business logic from technical implementation. This means you can easily switch between different frameworks and libraries without changing the core business logic. In our example, we can switch between koa and nestjs-app while keeping the same core business logic.

Code implementation

Define entity layer

// server/core/src/domain/post.ts
import { User } from "./user";

export class Post {
  author: User | null = null;
  content: string = "";
  updateAt: Date = new Date(); // timestamp;
  createdAt: Date = new Date(); // timestamp;
  title: string = "";
  id: number = -1;
}

// server/core/src/domain/user.ts
export class User {
  name: string = ''

  email: string = ''

  id: number = -1
}
Copy after login

Define storage interface

import { Post } from "../domain/post";

export interface IPostRepository {
  create(post: Post): Promise<boolean>;

  find(id: number): Promise<Post>;

  update(post: Post): Promise<boolean>;

  delete(post: Post): Promise<boolean>;

  findMany(options: { authorId: number }): Promise<Post[]>;
}

...
import { User } from "../domain/user";

export interface IUserRepository {
  create(user: User): Promise<boolean>;
  find(id: number): Promise<User>;
}
Copy after login

Define the use case layer

import { User } from "../domain/user";
import { IUserRepository } from "../repository/user";

export class UCUser {
  constructor(public userRepo: IUserRepository) {}

  find(id: number) {
    return this.userRepo.find(id);
  }

  create(name: string, email: string) {
    if (email.includes("@test.com")) {
      const user = new User();
      user.email = email;
      user.name = name;
      return this.userRepo.create(user);
    }
    throw Error("Please use legal email");
  }
}
Copy after login

koa project

Implement the storage layer interface in the koa project

// server/koa/src/user/user.repo.ts
import { PrismaClient } from "@prisma/client";
import { IUserRepository, User } from "core";

export class UserRepository implements IUserRepository {
  prisma = new PrismaClient();

  async create(user: User): Promise<boolean> {
    const d = await this.prisma.user_orm_entity.create({
      data: {
        email: user.email,
        name: user.name,
      },
    });

    return !!d;
  }

  async find(id: number): Promise<User> {
    const d = await this.prisma.user_orm_entity.findFirst({
      where: {
        id: id,
      },
    });

    if (d) {
      const u = new User();
      u.email = d?.email;
      u.id = d?.id;
      u.name = d?.name;
      return u;
    }
    throw Error("user id " + id + "not found");
  }
}
Copy after login

Implementing HTTP routing (presentation layer) in koa project

// server/koa/src/user/user.controller.ts
import Router from "@koa/router";
import { UCUser } from "core";
import { UserRepository } from "./user.repo";

export const userRouter = new Router({
  prefix: "/user",
});

userRouter.get("/:id", async (ctx, next) => {
  try {
    const service = new UCUser(new UserRepository());
    if (ctx.params.id) {
      const u = await service.find(+ctx.params.id);
      ctx.response.body = JSON.stringify(u);
    }
  } catch (e) {
    ctx.throw(400, "some error on get user", e.message);
  }
  await next();
});
Copy after login
nest-js project

An example of nestjs project can be found here Found in the path (

github.com/lulusir/cle…

I won’t post the code here

Finally

Please note that in the actual project, we will not put the core business logic in a separate warehouse (i.e. core), this is just to demonstrate the performance under different frameworks Use the same business logic

By decoupling business logic from the framework, you can easily switch between different frameworks and libraries without changing the core business logic. If you want to build scalable and maintainable applications, Clean Architecture is definitely worth considering.

If you want to demonstrate how to connect to other frameworks, you can put forward the

project address in the comment area (github.com/lulusir/cle... I think it’s a good idea, You can give a star, thank you

For more node-related knowledge, please visit:nodejs tutorial!

The above is the detailed content of What is Clean Architecture? How to implement it with Node?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

What is the architecture and working principle of Spring Data JPA? What is the architecture and working principle of Spring Data JPA? Apr 17, 2024 pm 02:48 PM

SpringDataJPA is based on the JPA architecture and interacts with the database through mapping, ORM and transaction management. Its repository provides CRUD operations, and derived queries simplify database access. Additionally, it uses lazy loading to only retrieve data when necessary, thus improving performance.

1.3ms takes 1.3ms! Tsinghua's latest open source mobile neural network architecture RepViT 1.3ms takes 1.3ms! Tsinghua's latest open source mobile neural network architecture RepViT Mar 11, 2024 pm 12:07 PM

Paper address: https://arxiv.org/abs/2307.09283 Code address: https://github.com/THU-MIG/RepViTRepViT performs well in the mobile ViT architecture and shows significant advantages. Next, we explore the contributions of this study. It is mentioned in the article that lightweight ViTs generally perform better than lightweight CNNs on visual tasks, mainly due to their multi-head self-attention module (MSHA) that allows the model to learn global representations. However, the architectural differences between lightweight ViTs and lightweight CNNs have not been fully studied. In this study, the authors integrated lightweight ViTs into the effective

How steep is the learning curve of golang framework architecture? How steep is the learning curve of golang framework architecture? Jun 05, 2024 pm 06:59 PM

The learning curve of the Go framework architecture depends on familiarity with the Go language and back-end development and the complexity of the chosen framework: a good understanding of the basics of the Go language. It helps to have backend development experience. Frameworks that differ in complexity lead to differences in learning curves.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Hand-tearing Llama3 layer 1: Implementing llama3 from scratch Hand-tearing Llama3 layer 1: Implementing llama3 from scratch Jun 01, 2024 pm 05:45 PM

1. Architecture of Llama3 In this series of articles, we implement llama3 from scratch. The overall architecture of Llama3: Picture the model parameters of Llama3: Let's take a look at the actual values ​​of these parameters in the Llama3 model. Picture [1] Context window (context-window) When instantiating the LlaMa class, the variable max_seq_len defines context-window. There are other parameters in the class, but this parameter is most directly related to the transformer model. The max_seq_len here is 8K. Picture [2] Vocabulary-size and AttentionL

See all articles