In-memory command bus implementation.

Provides a simple, synchronous command bus for handling commands. Each command type can have only one handler.

const commandBus = new InMemoryCommandBus();

// Register handler
commandBus.register(CreateUserCommand, async (cmd) => {
const user = await userRepository.create(cmd.email, cmd.name);
return user.id;
});

// Dispatch command
const userId = await commandBus.dispatch(new CreateUserCommand('john@example.com', 'John'));

Implements

  • CommandBus

Constructors

Methods

  • Registers a command handler.

    Type Parameters

    • TCommand extends Command

      The command type

    • TResult = void

      The result type

    Parameters

    Returns void

    If a handler is already registered for this command type

    commandBus.register(CreateUserCommand, async (cmd) => {
    return await createUser(cmd.email, cmd.name);
    });
  • Dispatches a command to its registered handler.

    Type Parameters

    • TResult = void

      The result type

    Parameters

    • command: Command

      The command to dispatch

    Returns Promise<TResult>

    The result from the command handler

    If no handler is registered for this command type

    const result = await commandBus.dispatch(new CreateUserCommand('john@example.com', 'John'));
    
  • Checks if a handler is registered for a command type.

    Parameters

    • commandType: new (...args: never[]) => Command

      The command class constructor

    Returns boolean

    True if a handler is registered

  • Unregisters a command handler.

    Parameters

    • commandType: new (...args: never[]) => Command

      The command class constructor

    Returns boolean

    True if a handler was unregistered