使用Node.js實(shí)現(xiàn)Clean?Architecture方法示例詳解
Clean Architecture
Clean Architecture 是 Robert C. Martin 提出的一種軟件架構(gòu)模式,目的是為了將系統(tǒng)分層,實(shí)現(xiàn)關(guān)注點(diǎn)分離,使系統(tǒng)更易于理解、維護(hù)和擴(kuò)展。該體系結(jié)構(gòu)將系統(tǒng)分為四個(gè)層級(jí),從內(nèi)到外分別是:實(shí)體層、用例層、表現(xiàn)層、基礎(chǔ)設(shè)施(存儲(chǔ)庫,框架等)。

在本文中,我們將介紹如何使用 Node.js 實(shí)現(xiàn) Clean Architecture,并提供一些示例代碼來演示該架構(gòu)的關(guān)鍵概念。
接下來我們將使用 TypeScript 項(xiàng)目示例(github.com/lulusir/cle… )。該項(xiàng)目采用了 Monorepo 結(jié)構(gòu),使用 Rush.js 進(jìn)行管理。在 server 文件夾中包含了三個(gè)子項(xiàng)目,分別為 core、koa 和 nestjs-app,其中 core 為核心業(yè)務(wù)邏輯,koa是使用koa+prisma的為底層框架web項(xiàng)目,nestjs-app是使用nestjs + typeorm為底層框架的項(xiàng)目。目的是演示相同的業(yè)務(wù)邏輯如何橋接不同的框架。
在這個(gè)項(xiàng)目中,實(shí)體層包含實(shí)體對(duì)象和相關(guān)的業(yè)務(wù)規(guī)則和邏輯,用例層包含系統(tǒng)的用例和業(yè)務(wù)邏輯,存儲(chǔ)庫層負(fù)責(zé)保存和檢索數(shù)據(jù),表示層則是暴露給外部的http接口。
項(xiàng)目功能:
實(shí)現(xiàn)一個(gè)帖子發(fā)布,瀏覽功能
- 用戶創(chuàng)建,查詢
- 帖子的發(fā)布,編輯,查詢,刪除
項(xiàng)目結(jié)構(gòu)
├── server │ ├── core // 核心業(yè)務(wù)邏輯 │ │ └── src │ │ ├── domain │ │ ├── repository │ │ └── useCase │ ├── koa │ │ └── src │ │ ├── post │ │ └── user │ └── nestjs-app │ ├── src │ ├── post │ │ ├── dto │ │ └── entities │ └── user │ └── entities └── web
core:core為核心業(yè)務(wù)邏輯的代碼
- Domain: 存放實(shí)體相關(guān)的代碼,如業(yè)務(wù)具體的 model 等
- Use Cases: 存放業(yè)務(wù)邏輯相關(guān)的代碼,如處理業(yè)務(wù)邏輯、數(shù)據(jù)驗(yàn)證、調(diào)用 Repository 等
- Repository: 存放和外部存儲(chǔ)系統(tǒng)的相關(guān)接口
koa/nestjs-app: core的實(shí)際消費(fèi)者
- 根據(jù)core的接口實(shí)現(xiàn)具體的Router,Repository
項(xiàng)目特點(diǎn)
- 使用 DDD 和 Clean Architecture 的思想,將業(yè)務(wù)邏輯與框架實(shí)現(xiàn)分離。
- 使用 monorepo 項(xiàng)目結(jié)構(gòu),方便管理多個(gè)相關(guān)的項(xiàng)目。
- 提供了多個(gè)示例應(yīng)用程序,方便快速上手。
- 基于 TypeScript,提高代碼可讀性和可維護(hù)性。
在core中,我們有核心的業(yè)務(wù)邏輯代碼。此級(jí)別包含域、存儲(chǔ)庫接口和用例。域包含與實(shí)體相關(guān)的代碼,例如特定的業(yè)務(wù)模型。存儲(chǔ)庫包含與外部存儲(chǔ)系統(tǒng)的相關(guān)接口。用例包含與業(yè)務(wù)邏輯相關(guān)的代碼,例如處理業(yè)務(wù)邏輯、數(shù)據(jù)驗(yàn)證和調(diào)用存儲(chǔ)庫。
在koa/nestjs-app層面,我們有核心層面的實(shí)際消費(fèi)者。它們根據(jù)核心層提供的接口實(shí)現(xiàn)特定的路由器和存儲(chǔ)庫。 使用 Clean Architecture 的主要優(yōu)點(diǎn)之一是它將業(yè)務(wù)邏輯與技術(shù)實(shí)現(xiàn)分開。這意味著您可以輕松地在不同的框架和庫之間切換,而無需更改核心業(yè)務(wù)邏輯。在我們的示例中,我們可以在 koa 和 nestjs-app 之間切換,同時(shí)保持相同的核心業(yè)務(wù)邏輯。
代碼實(shí)現(xiàn)
定義實(shí)體層
// 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
}
定義存儲(chǔ)接口
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>;
}
定義用例層
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");
}
}
koa項(xiàng)目
在koa項(xiàng)目中實(shí)現(xiàn)存儲(chǔ)層接口
// 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");
}
}
在koa項(xiàng)目中實(shí)現(xiàn)HTTP路由(表現(xiàn)層)
// 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();
});
nest-js項(xiàng)目
nestjs 項(xiàng)目的示例可以在此路徑中找到 (github.com/lulusir/cle… 就不在這里貼代碼了
最后
請(qǐng)注意,在實(shí)際項(xiàng)目中,我們不會(huì)將核心業(yè)務(wù)邏輯放在單獨(dú)的倉庫中(即core),這只是為了演示在不同框架下使用相同的業(yè)務(wù)邏輯
通過將業(yè)務(wù)邏輯與框架分離,您可以輕松地在不同的框架和庫之間切換,而無需更改核心業(yè)務(wù)邏輯。如果您希望構(gòu)建可擴(kuò)展且可維護(hù)的應(yīng)用程序,那么Clean Architecture 絕對(duì)值得考慮。
如果想要演示如何接入其他框架,可以在評(píng)論區(qū)提出
項(xiàng)目地址 (github.com/lulusir/cle… 覺得不錯(cuò)的小伙伴,可以給個(gè)star,謝謝
以上就是使用Node.js實(shí)現(xiàn)Clean Architecture方法示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Node.js Clean Architecture的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用nodejs搭建一個(gè)簡(jiǎn)易HTTP服務(wù)的實(shí)現(xiàn)示例
本文主要介紹了使用nodejs搭建一個(gè)簡(jiǎn)易HTTP服務(wù)的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
利用Node.js制作爬取大眾點(diǎn)評(píng)的爬蟲
相信每位用過大眾點(diǎn)評(píng)的人都知道,大眾點(diǎn)評(píng)上有很多美食餐館的信息,所以這篇文章給大家分享利用Node.js實(shí)現(xiàn)爬取大眾點(diǎn)評(píng)的爬蟲,正好可以拿來練練手Node.js。感興趣的可以參考借鑒。2016-09-09
node.js連接mongoDB數(shù)據(jù)庫 快速搭建自己的web服務(wù)
這篇文章主要為大家詳細(xì)介紹了node.js連接mongoDB數(shù)據(jù)庫,如何快速搭建自己的web服務(wù),感興趣的小伙伴們可以參考一下2016-04-04
在Node.js中處理Promise中錯(cuò)誤的示例代碼
在現(xiàn)代JavaScript開發(fā)中,尤其在Node.js環(huán)境中,Promise已成為處理異步操作的重要方式,然而,Promise的錯(cuò)誤處理卻常常讓開發(fā)者感到困惑,在這篇文章中,我們將深入探討如何在Node.js中處理Promise中的錯(cuò)誤,提供多個(gè)示例代碼,以便于理解和實(shí)踐,需要的朋友可以參考下2024-09-09
Node.js?搭建后端服務(wù)器內(nèi)置模塊(?http+url+querystring?的使用)
這篇文章主要介紹了Node.js搭建后端服務(wù)器內(nèi)置模塊(http+url+querystring的使用),文章圍繞主題展開詳細(xì)的內(nèi)容戒殺,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-09-09
nodejs實(shí)現(xiàn)解析xml字符串為對(duì)象的方法示例
這篇文章主要介紹了nodejs實(shí)現(xiàn)解析xml字符串為對(duì)象的方法,涉及nodejs針對(duì)xml格式字符串的解析與轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下2018-03-03

