Skip to main content

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:
Timing: Runs before constructor completes, before any execution.

Use Cases

  • Change data before it is validated
  • Generate required values that are optional at input

Generating Required Values

Use onBeforeCreate 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:
Timing: Runs after constructor completes, after schema validation. Use cases:
  • Logging
  • Initializing computed values
  • Adding domain events
  • Setting up internal state

onBeforeUpdate

Called before a property change is applied. Return false to reject the change:
Timing: Runs before property change is finalized. Parameters:
  • entity: Current state (with proposed change)
  • snapshot: State before the change
Return value:
  • true or undefined: Allow the change
  • false: Reject the change (value reverts)

rules

Custom validation rules that run after schema validation:
Timing: Runs after schema validation, both on create and update. Use cases:
  • Cross-field validation
  • Business rule validation
  • Reserved value checks
  • Complex conditional rules

Collecting Validation Issues (Non-Throwing)

When throwOnError is false, accumulate issues in rules without throwing:
After construction or update, check entity.hasValidationErrors and entity.validationErrors?.getFormattedErrors() for UI display.

Throwing Validation Errors

Use throwValidationError helper in rules for fail-fast validation:
The helper throws a 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.

Real-World Examples

User Registration Rules

Order Business Rules

Inventory Rules