1
votes

I am trying to use events in my nestjs app.

However when I attempt to trigger command, I get CommandHandlerNotFoundException.

I have message-bus.module:

@Module({
    imports: [CqrsModule],
    providers: [
        MessageBusLocalService,
        StartWorkflowHandler
    ],
    exports: [MessageBusLocalService]
})
export class MessageBusModule {
}

message-bus-local.service

@Injectable()
export class MessageBusLocalService {

    constructor(private readonly commandBus: CommandBus, private eb: EventBus) {
    }

    startWorkflow(workflowId: string, payload: any) {
        return this.commandBus.execute(
            new StartWorkflowCommand(workflowId, payload)
        );
    }
}

and start-workflow.handler

@CommandHandler(StartWorkflowCommand)
export class StartWorkflowHandler implements ICommandHandler<StartWorkflowCommand> {
    constructor() {}

    async execute(command: StartWorkflowCommand) {
        console.log('Workflow started', command.jobId);
        return true;
    }
}

I am trying to trigger command when app is bootstrapped:

    const app = await NestFactory.create(ApplicationModule);

    const service = app.get(MessageBusLocalService);
    try {
        const c = await service.startWorkflow('abcde', {just: "test"});
        console.log('And returned', c);
    } catch (e) {
        console.error(e)
    }

and... I get the CommandHandlerNotFoundException there although I believe it is declared... What did I do wrong?

Thanks in advance.

4

4 Answers

0
votes

Your MessageBusModule does not re-export handlers, thus they are not "visible" on app.module level (at least this is what I understand on my own)

I got similar scenario like that:

const commands = [NewOrder, ChargeForOrder]
const events = [ChargeOrder, OrderProcessed]
const sagas = [AdjustWalletFunds]

@Module({
  imports: [
    CqrsModule,
    WalletsModule,
    TypeOrmModule.forFeature([...]),
  ],
  providers: [...commands, ...events, ...sagas],
  exports: [CqrsModule, ...commands, ...events, ...sagas],
})
export class RxModule {}

so, assuming you import your MessageBusModule in the main app.module, try the following:

@Module({
    imports: [CqrsModule],
    providers: [
        MessageBusLocalService,
        StartWorkflowHandler
    ],
    exports: [MessageBusLocalService, StartWorkflowHandler]
})
export class MessageBusModule {
}
0
votes

As it turns out, the method I used in the question does not work.

However it does work as expected if I inject the MessageBusLocalService in controller.

It seems odd to answer my own question but it might help someone eventually.

0
votes

Ensure you imported have CqrsModule imported. Also import the MessageBusModule into any other module where it is called from.

0
votes

Since you want to use the handler in another module (e.g. appModule ) you need to add the @Injectable() decorator to the StartWorkflowHandler class.

And call app.init() in the main.ts. Before starting the application.