2
votes

I am using nestjs in my app backend.I use the cqrs module https://github.com/nestjs/cqrs, I read that cqrs have a commands to write operations and queries to read operation but nestjs documentation (https://docs.nestjs.com/recipes/cqrs) only has a example of command so How Do I implement a queries in nestjs?

2

2 Answers

2
votes

Queries are handled by QueryHandlers. They implement IQueryHandler which requires that you have an async execute function. My personal preference is to return an Observable from a query handler that is being executed from a controller, which is fully supported in NestJS applications.

Here's an example Query:

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

Endpoint:

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

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

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

Query Handler:

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))
    );
  }
}

Query Handlers get placed in the providers section of a module, like this:

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

There is no single recommended solution. CQRS module is all about the write-side, whereas read-side is much simpler and less complex. Use whatever fits your requirements. https://github.com/nestjs/nest/issues/985