Event Sourcing Aggregate Root
Implement an event sourcing aggregate root that applies events to rebuild state with version tracking.
Code
abstract class AggregateRoot{private events:any[]=[];version=0;protected abstract apply(event:any):void;loadFromHistory(events:any[]):void{for(const e of events){this.apply(e);this.version++;}}commit():any[]{const pending=this.events;this.events=[];return pending;}raise(event:any):void{this.apply(event);this.events.push(event);this.version++;}}export class CounterAggregate extends AggregateRoot{value=0;protected apply(event:any):void{if(event.type==='incremented')this.value+=event.amount;else if(event.type==='decremented')this.value-=event.amount;}increment(amount:number){this.raise({type:'incremented',amount});}decrement(amount:number){this.raise({type:'decremented',amount});}}How it works
The working surface is the classes AggregateRoot and CounterAggregate — everything else is wiring.
Putting it to use
CounterAggregate is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared.
Report a problem with this exampleOpens a pre-filled issue on GitHub.