Overview
Hooks provide a way to add custom logic at specific points in an entity’s lifecycle. They complement schema validation with business rules that can’t be expressed in a schema.Available Hooks
onBeforeCreate
Usage
Called before the entity is created and validated:Use Cases
- Change data before it is validated
- Generate required values that are optional at input
Generating Required Values
UseonBeforeCreate with optional input properties to generate values internally:
Values generated in
onBeforeCreate are still validated by the schema. If generation fails to meet schema requirements, a ValidationError will be thrown.onCreate
Called after the entity is successfully created and validated:- Logging
- Initializing computed values
- Adding domain events
- Setting up internal state
onBeforeUpdate
Called before a property change is applied. Returnfalse to reject the change:
entity: Current state (with proposed change)snapshot: State before the change
trueorundefined: Allow the changefalse: Reject the change (value reverts)
rules
Custom validation rules that run after schema validation:- Cross-field validation
- Business rule validation
- Reserved value checks
- Complex conditional rules
Collecting Validation Issues (Non-Throwing)
WhenthrowOnError is false, accumulate issues in rules without throwing:
entity.hasValidationErrors and entity.validationErrors?.getFormattedErrors() for UI display.
Throwing Validation Errors
UsethrowValidationError helper in rules for fail-fast validation:
ValidationError with proper structure:
Combining Schema and Hooks
Schema validation runs first, then hooks:Execution Order
Hooks for Value Objects
Value Objects support hooks for primitive values:Value Objects don’t have
onBeforeUpdate because they’re immutable - you
create new instances instead of modifying.