NestJS下的CQRS实现 - Command基础

前一篇讲述了NestJS中CQRS的Query部分的实现,本文会在此基础上讲述Command部分的基础实现(高级实现会在下一篇介绍)。

在之前代码的基础上增加:
src/comments/commands文件夹,结构如下:

add-comment.handler.ts

import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { AddCommentCommand } from '../impl/add-comment.command';

@CommandHandler(AddCommentCommand)
export class AddCommentHandler implements ICommandHandler<AddCommentCommand> {
  async execute(command: AddCommentCommand) {
    console.log(`AddCommentHandler, personId: ${command.personId}, comment: ${command.comment}`);
  }
}

index.ts

import { AddCommentHandler } from './add-comment.handler';

export const CommandHandlers = [AddCommentHandler];

add-comment.command.ts

export class AddCommentCommand {
    constructor(
      public readonly comment: string,
      public readonly personId: string,
    ) {}
  }

models/comment.model.ts 增加如下代码

export interface AddCommentDTO {
  comment: string;
}

comments.controller.ts

import { Controller, Get, Post, Param, Body } from '@nestjs/common';
import { QueryBus, CommandBus } from '@nestjs/cqrs';
import { Comment } from './models/comment.model';
import { GetCommentQuery } from './queries/impl';
import { AddCommentCommand } from './commands/impl/add-comment.command';
import { AddCommentDTO } from './models/comment.model';

@Controller('comments')
export class CommentsController {
    constructor(
        private readonly commandBus: CommandBus,
        private readonly queryBus: QueryBus,
      ) {}

    @Get()
    async findAll(): Promise<Comment> {
      return this.queryBus.execute(new GetCommentQuery());
    }

    @Post(':id/add')
    async killDragon(@Param('id') id: string, @Body() dto: AddCommentDTO) {
      console.log(`comment controller, json: ${JSON.stringify(dto)}`)
      return this.commandBus.execute(new AddCommentCommand(dto.comment, id));
    }
}

comments.module.ts

import { Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { CommentsController } from './comments.controller';
import { QueryHandlers } from './queries/handlers';
import { CommandHandlers } from './commands/handlers';

@Module({
  imports: [CqrsModule],
  controllers: [CommentsController],
  providers: [
    ...QueryHandlers,
    ...CommandHandlers,
  ],
})
export class CommentsModule {}

运行npm run start
打开postman,发送post请求

查看控制台输出

到目前为止Command模式与Query模式大同小异,下篇文章我们会再探究一下Command模式的一些高级用法。

示例代码链接

posted @ 2021-09-06 17:36  老胡Andy  阅读(253)  评论(0编辑  收藏  举报