In the CQRS pattern used by this library, Commands and Command Handlers separate intent from execution:
- Command: A simple data object representing a user or system's intent to change the state of the system (e.g.,
OpenAccountCommand). It should use imperative language and carry only the data required for the action. - CommandHandler: A class containing the business logic required to execute a specific command. It interacts with domain aggregates and repositories to perform the action and persist changes.
Commands are intended to trigger state changes, whereas queries (which are handled separately) are used to retrieve data.
// A Command represents intent
export class CreditAccountCommand implements ICommand {
constructor(
public readonly accountId: string,
public readonly amount: number,
) {}
}
// A CommandHandler executes the intent
@CommandHandler(CreditAccountCommand)
export class CreditAccountCommandHandler implements ICommandHandler {
async execute(command: CreditAccountCommand): Promise<boolean> {
// Logic to interact with aggregates and repositories goes here
}
}