Bus for dispatching commands to their handlers.

Ensures that each command is handled by exactly one handler.

// Register handler
commandBus.register(CreateUserCommand, new CreateUserCommandHandler());

// Dispatch command
const user = await commandBus.dispatch<User>(
new CreateUserCommand('user@example.com', 'John Doe')
);
interface CommandBus {
    register<TCommand extends Command, TResult = void>(
        commandType: new (...args: unknown[]) => TCommand,
        handler: CommandHandler<TCommand, TResult>,
    ): void;
    dispatch<TResult = void>(command: Command): Promise<TResult>;
}

Methods

  • Dispatches a command to its registered handler.

    Type Parameters

    • TResult = void

      The expected result type

    Parameters

    • command: Command

      The command to dispatch

    Returns Promise<TResult>

    The result from the command handler

    Error if no handler is registered for the command

    const command = new CreateUserCommand('user@example.com', 'John');
    const user = await commandBus.dispatch<User>(command);