## CQRS
可以用下列步驟來描述一個簡單的 **[CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete)** 應用程序流程:
1. **控制器層**處理 HTTP 請求并將任務委派給服務層。
2. **服務層**是處理大部分業務邏輯。
3. 服務使用**存儲庫或 DAOs** 來更改/保存實體。
4. 實體充當值的容器,具有 `setter` 和 `getter` 。
在大部分情況下,這種模式對中小型應用來說是足夠的。然而,當我們的需求變得更加復雜時,**CQRS** 模型可能更合適并且易于擴展。
為了簡化這個模型,`Nest` 提供了一個輕量級的 [CQRS](https://github.com/nestjs/cqrs) 模塊,本章描述如何使用它。
### 安裝
首先安裝需要的包
```bash
$ npm install --save @nestjs/cqrs
```
### 指令
在本模塊中,每個行為都被稱為一個 **Command** 。當任何命令被分派時,應用程序必須對其作出反應。命令可以從服務中分派(或直接來自控制器/網關)并在相應的 **Command 處理程序** 中使用。
> heroes-game.service.ts
```typescript
@Injectable()
export class HeroesGameService {
constructor(private commandBus: CommandBus) {}
async killDragon(heroId: string, killDragonDto: KillDragonDto) {
return this.commandBus.execute(
new KillDragonCommand(heroId, killDragonDto.dragonId)
);
}
}
```
這是一個示例服務, 它調度 `KillDragonCommand` 。讓我們來看看這個命令:
> kill-dragon.command.ts
```typescript
export class KillDragonCommand {
constructor(
public readonly heroId: string,
public readonly dragonId: string,
) {}
}
```
這個 `CommandBus` 是一個命令 **流** 。它將命令委托給等效的處理程序。每個命令必須有相應的命令處理程序:
> kill-dragon.handler.ts
```typescript
@CommandHandler(KillDragonCommand)
export class KillDragonHandler implements ICommandHandler<KillDragonCommand> {
constructor(private repository: HeroRepository) {}
async execute(command: KillDragonCommand) {
const { heroId, dragonId } = command;
const hero = this.repository.findOneById(+heroId);
hero.killEnemy(dragonId);
await this.repository.persist(hero);
}
}
```
現在,每個應用程序狀態更改都是**Command**發生的結果。 邏輯封裝在處理程序中。 如果需要,我們可以簡單地在此處添加日志,甚至更多,我們可以將命令保留在數據庫中(例如用于診斷目的)。
### 事件(Events)
由于我們在處理程序中封裝了命令,所以我們阻止了它們之間的交互-應用程序結構仍然不靈活,不具有**響應性**。解決方案是使用**事件**。
> hero-killed-dragon.event.ts
```typescript
export class HeroKilledDragonEvent {
constructor(
public readonly heroId: string,
public readonly dragonId: string,
) {}
}
```
事件是異步的。它們可以通過**模型**或直接使用 `EventBus` 發送。為了發送事件,模型必須擴展 `AggregateRoot` 類。。
> hero.model.ts
```typescript
export class Hero extends AggregateRoot {
constructor(private readonly id: string) {
super();
}
killEnemy(enemyId: string) {
// logic
this.apply(new HeroKilledDragonEvent(this.id, enemyId));
}
}
```
`apply()` 方法尚未發送事件,因為模型和 `EventPublisher` 類之間沒有關系。如何關聯模型和發布者? 我們需要在我們的命令處理程序中使用一個發布者 `mergeObjectContext()` 方法。
> kill-dragon.handler.ts
```typescript
@CommandHandler(KillDragonCommand)
export class KillDragonHandler implements ICommandHandler<KillDragonCommand> {
constructor(
private repository: HeroRepository,
private publisher: EventPublisher,
) {}
async execute(command: KillDragonCommand) {
const { heroId, dragonId } = command;
const hero = this.publisher.mergeObjectContext(
await this.repository.findOneById(+heroId),
);
hero.killEnemy(dragonId);
hero.commit();
}
}
```
現在,一切都按我們預期的方式工作。注意,我們需要 `commit()` 事件,因為他們不會立即被發布。顯然,對象不必預先存在。我們也可以輕松地合并類型上下文:
```typescript
const HeroModel = this.publisher.mergeContext(Hero);
new HeroModel('id');
```
就是這樣。模型現在能夠發布事件。我們得處理他們。此外,我們可以使用 `EventBus` 手動發出事件。
```typescript
this.eventBus.publish(new HeroKilledDragonEvent());
```
> `EventBus` 是一個可注入的類。
每個事件都可以有許多事件處理程序。
> hero-killed-dragon.handler.ts
```typescript
@EventsHandler(HeroKilledDragonEvent)
export class HeroKilledDragonHandler implements IEventHandler<HeroKilledDragonEvent> {
constructor(private readonly repository: HeroRepository) {}
handle(event: HeroKilledDragonEvent) {
// logic
}
}
```
現在,我們可以將寫入邏輯移動到事件處理程序中。
### Sagas
這種類型的 **事件驅動架構** 可以提高應用程序的 **反應性** 和 **可伸縮性** 。現在, 當我們有了事件, 我們可以簡單地以各種方式對他們作出反應。**Sagas**是建筑學觀點的最后一個組成部分。
`sagas` 是一個非常強大的功能。單 `saga` 可以監聽 1..* 事件。它可以組合,合并,過濾事件流。[RxJS](https://github.com/ReactiveX/rxjs) 庫是`sagas`的來源地。簡單地說, 每個 `sagas` 都必須返回一個包含命令的Observable。此命令是 **異步** 調用的。
> heroes-game.saga.ts
```typescript
@Injectable()
export class HeroesGameSagas {
@Saga()
dragonKilled = (events$: Observable<any>): Observable<ICommand> => {
return events$.pipe(
ofType(HeroKilledDragonEvent),
map((event) => new DropAncientItemCommand(event.heroId, fakeItemID)),
);
}
}
```
?> `ofType` 運算符從 `@nestjs/cqrs` 包導出。
我們宣布一個規則 - 當任何英雄殺死龍時,古代物品就會掉落。 之后,`DropAncientItemCommand` 將由適當的處理程序調度和處理。
### 查詢
`CqrsModule` 對于查詢處理可能也很方便。 `QueryBus` 與 `CommandsBus` 的工作方式相同。 此外,查詢處理程序應實現 `IQueryHandler` 接口并使用 `@QueryHandler()` 裝飾器進行標記。
### 建立
我們要處理的最后一件事是建立整個機制。
> heroes-game.module.ts
```typescript
export const CommandHandlers = [KillDragonHandler, DropAncientItemHandler];
export const EventHandlers = [HeroKilledDragonHandler, HeroFoundItemHandler];
@Module({
imports: [CqrsModule],
controllers: [HeroesGameController],
providers: [
HeroesGameService,
HeroesGameSagas,
...CommandHandlers,
...EventHandlers,
HeroRepository,
]
})
export class HeroesGameModule {}
```
### 概要
`CommandBus` ,`QueryBus` 和 `EventBus` 都是**Observables**。這意味著您可以輕松地訂閱整個流, 并通過 **Event Sourcing** 豐富您的應用程序。
完整的源代碼在[這里](https://github.com/kamilmysliwiec/nest-cqrs-example) 。
- 介紹
- 概述
- 第一步
- 控制器
- 提供者
- 模塊
- 中間件
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 自定義裝飾器
- 基礎知識
- 自定義提供者
- 異步提供者
- 動態模塊
- 注入作用域
- 循環依賴
- 模塊參考
- 懶加載模塊
- 應用上下文
- 生命周期事件
- 跨平臺
- 測試
- 技術
- 數據庫
- Mongo
- 配置
- 驗證
- 緩存
- 序列化
- 版本控制
- 定時任務
- 隊列
- 日志
- Cookies
- 事件
- 壓縮
- 文件上傳
- 流式處理文件
- HTTP模塊
- Session(會話)
- MVC
- 性能(Fastify)
- 服務器端事件發送
- 安全
- 認證(Authentication)
- 授權(Authorization)
- 加密和散列
- Helmet
- CORS(跨域請求)
- CSRF保護
- 限速
- GraphQL
- 快速開始
- 解析器(resolvers)
- 變更(Mutations)
- 訂閱(Subscriptions)
- 標量(Scalars)
- 指令(directives)
- 接口(Interfaces)
- 聯合類型
- 枚舉(Enums)
- 字段中間件
- 映射類型
- 插件
- 復雜性
- 擴展
- CLI插件
- 生成SDL
- 其他功能
- 聯合服務
- 遷移指南
- Websocket
- 網關
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 適配器
- 微服務
- 概述
- Redis
- MQTT
- NATS
- RabbitMQ
- Kafka
- gRPC
- 自定義傳輸器
- 異常過濾器
- 管道
- 守衛
- 攔截器
- 獨立應用
- Cli
- 概述
- 工作空間
- 庫
- 用法
- 腳本
- Openapi
- 介紹
- 類型和參數
- 操作
- 安全
- 映射類型
- 裝飾器
- CLI插件
- 其他特性
- 遷移指南
- 秘籍
- CRUD 生成器
- 熱重載
- MikroORM
- TypeORM
- Mongoose
- 序列化
- 路由模塊
- Swagger
- 健康檢查
- CQRS
- 文檔
- Prisma
- 靜態服務
- Nest Commander
- 問答
- Serverless
- HTTP 適配器
- 全局路由前綴
- 混合應用
- HTTPS 和多服務器
- 請求生命周期
- 常見錯誤
- 實例
- 遷移指南
- 發現
- 誰在使用Nest?