Command Bus
The Command Bus implements the Command Query Responsibility Segregation (CQRS) pattern for handling commands. Commands represent intentions to modify state and are handled by registered handlers.
Example: User Management Commands
import {
Command,
HybridCommandBus,
type CommandHandlerInterface,
} from "@dxbox/use-less-react/classes";
// Define command payload
interface CreateUserPayload {
email: string;
name: string;
password: string;
}
// Create command class
class CreateUserCommand extends Command<"CreateUser", CreateUserPayload> {
get type(): "CreateUser" {
return "CreateUser";
}
}
// Define command handler
class CreateUserHandler implements CommandHandlerInterface<CreateUserCommand> {
async handle(command: CreateUserCommand): Promise<void> {
const { email, name, password } = command.payload;
// Perform the command action (e.g., save to database)
await this.userRepository.create({
email,
name,
password: await this.hashPassword(password),
});
// Optionally publish events after command execution
await this.eventBus.publish(
new UserCreatedEvent({ userId: command.id, email })
);
}
constructor(
private userRepository: UserRepository,
private eventBus: EventBus
) {}
}
// Setup command bus
const commandBus = new HybridCommandBus({
monitoringService: myMonitoringService,
});
// Register handler
commandBus.registerLocalHandler("CreateUser", new CreateUserHandler(...));
// Dispatch command
const command = new CreateUserCommand({
email: "user@example.com",
name: "John Doe",
password: "secure123",
});
await commandBus.dispatch(command);
API
HybridCommandBus
registerLocalHandler<T>(commandType: T["type"], handler: CommandHandlerInterface<T>): void- Register a handler for a command typedispatch(command: UntypedCommandType): Promise<void>- Dispatch a command to its handler
Command
id: string- Unique command identifier (optional, gets default value)timestamp: Date- Command creation timestamp (optional, gets default value)type: TType- Command type (must be implemented by subclass)payload: TPayload- Command payload data
CommandHandlerInterface
handle(command: TCommand): Promise<void>- Handle the command