Reputation: 303
I am new to nodejs and am trying to implement NestJS's CQRS 'recipe'. I have a service with Request
scope with QueryBus
injection:
@Injectable({scope: Scope.REQUEST})
export class CustomerService {
constructor(
@Inject(REQUEST) private readonly req: Request,
private readonly queryBus: QueryBus,
) {}
I have defined a handler class CustomerHandler
to handle CustomerQuery
:
@QueryHandler(CustomerQuery)
export class CustomerHandler implements IQueryHandler<CustomerQuery> {
constructor(
private readonly repository: CustomerRepository,
) {}
async execute(query: CustomerQuery) {
const {response, id, name} = query;
this.repository.getCustomer(response, id, name);
}
But upon execution I got an error message:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getCustomer' of undefined at CustomerHandler.execute
which means, if I am not wrong, repository injection failed. (which caused code to fail for statement this.repository.getCustomer(response, id, name);
)
I have added my repository class CustomerRepository
in providers
array of my module CustomerModule
:
@Module({
imports: [Logger, CqrsModule],
providers: [CustomerService, ...QueryHandlers, CustomerRepository],
exports: [CustomerService],
})
export class CustomerModule {}
Here's my repository class, for reference:
@Injectable()
export class CustomerRepository {
constructor(
@Inject(REQUEST) private readonly req: Request,
) {}
Am I missing something here? Why is my repository class not being instantiated, if thats not the case, why is the repository injection failing in handler. Any input would be appreciated :)
Documentaion I am following: https://docs.nestjs.com/recipes/cqrs
Github example I referred: https://github.com/kamilmysliwiec/nest-cqrs-example
EDIT:
Handler (CustomerHandler
) is not able to perform any sort of injection. I tried injecting logger (PinoLogger
), which led to similar issue. So, it looks like, the problem is not with CustomerRepository
, but with CustomerHandler
.
UPDATE:
So basically, the problem is that every CqrsModule provider is statically scoped which mean that they cannot depend on request-scoped providers. Once you define your command handler as a request-scoped provider, either CommandBus or QueryBus won't be able to reference it. This is not an issue, but rather a design decision that sits behind the entire module.
Source: https://github.com/nestjs/cqrs/issues/60#issuecomment-483288297
i.e. @QueryHandler()
cannot be request scoped (source: comment on question - NestJS undefined dependencies and answer to the same https://stackoverflow.com/a/61916353/10011503).
And, this is also an open issue.
Upvotes: 2
Views: 2781
Reputation: 11
Reading nestjs doc, i saw that all handlers for command and query handlers are resolve en default scope, so, all dependencies with request or trasient scope are not provide in handlers. Solution is inject factory objects that resolve dependencies when are necesary
Upvotes: 1