Command Query Responsibility Segregation (CQRS) separates read and write operations for better scalability and performance.
Decouple write operations.
Segregate read operations.
Async event processing.
Manage long-running processes.
1import { ICommand, CommandHandler, ICommandHandler, CommandBus } from "canxjs";23export class CreateUserCommand implements ICommand {4type = 'CreateUser';5constructor(public readonly name: string) {}6}78@CommandHandler('CreateUser')9export class CreateUserHandler implements ICommandHandler<CreateUserCommand> {10async execute(command: CreateUserCommand): Promise<void> {11console.log("Creating user:", command.name);12}13}1415// In your controller:16await commandBus.execute(new CreateUserCommand("Alice"));
1import { IQuery, QueryHandler, IQueryHandler } from "canxjs";23export class GetUserQuery implements IQuery {4type = 'GetUser';5constructor(public readonly id: string) {}6}78@QueryHandler('GetUser')9export class GetUserHandler implements IQueryHandler<GetUserQuery> {10async execute(query: GetUserQuery) {11return { id: query.id, name: "Alice" };12}13}
Sagas orchestrate complex workflows by listening to events and dispatching commands.
1import { EventHandler, IEvent, ISaga, ICommand } from "canxjs";23@EventHandler('UserCreated')4export class UserSagas implements ISaga {56// React to events and dispatch commands7async *handle(event: IEvent): AsyncGenerator<ICommand> {8if (event.type === 'UserCreated') {9yield new SendWelcomeEmailCommand(event.userId);10}11}12}