gpt4 book ai didi

node.js - 如何使用cqrs模块在nestjs中进行查询?

转载 作者:行者123 更新时间:2023-12-02 03:30:50 24 4
gpt4 key购买 nike

我在我的应用程序后端使用nestjs。我使用cqrs模块https://github.com/nestjs/cqrs ,我读到 cqrs 有一个命令来写入操作和查询来读取操作,但 Nestjs 文档( https://docs.nestjs.com/recipes/cqrs )只有一个命令示例,所以我如何实现在nestjs中查询?

最佳答案

查询由 QueryHandlers 处理。它们实现了 IQueryHandler ,这要求您有一个异步 execute 函数。我个人的偏好是从 Controller 执行的查询处理程序返回一个 Observablewhich is fully supported in NestJS applications .

这是一个示例查询:

class GetSomeStuff {
constructor(
readonly id: string;
) {}
}

端点:

import { QueryBus } from '@nestjs/cqrs';

class SomeController {
constructor(private queryBus: QueryBus) {}

@Get('some-stuff')
getSomeStuff() {
return this.queryBus.execute(new GetSomeStuff('foo_id'));
}
}

查询处理程序:

import { GetSomeStuff } from '@app/shared/util-queries';
import { SharedStuffDataService } from '@app/shared/stuff/data-access'
import { GetSomeStuffDto } from '@app/shared/util-models';
import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { from } from 'rxjs';
import { map } from 'rxjs/operators';

@QueryHandler(GetSomeStuff)
export class GetSomeStuffHandler implements IQueryHandler<GetSomeStuff> {
constructor(
private readonly dataService: SharedStuffDataService,
) {}

async execute(query: GetSomeStuff) {
const stuffRepo = this.dataService.connectToReadModel();

return from(stuffRepo.getOneById(query.id)).pipe(
map(stuff => new GetSomeStuffDto(stuff))
);
}
}

查询处理程序被放置在模块的providers部分,如下所示:

@Module({
imports: [
CqrsModule,
SharedStuffDataModule,
],
providers: [ GetSomeStuffHandler ],
})
export class QueriesModule {}

关于node.js - 如何使用cqrs模块在nestjs中进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51909358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com