-
Notifications
You must be signed in to change notification settings - Fork 0
Aggregators
The Aggregator interface is a fundamental component in es4j event sourcing architecture. Responsible for applying events to aggregates and also facilitating event schema migration, the Aggregator helps maintain the integrity and evolution of your domain models.
The Aggregator interface specifies the contract that an implementing class must fulfill. It uses Java generics to define the types for the aggregate (T) and the event (E), both of which must implement the Aggregate and Event interfaces, respectively.
public interface Aggregator<T extends Aggregate, E extends Event> {
// method definitions
}This method takes an aggregate's current state and an event, then returns the updated state of the aggregate after applying the event.
T apply(T aggregateState, E event);Parameters:
-
aggregateState: The existing state of the aggregate. -
event: The event to be applied to the aggregate.
Returns:
- An updated state of the aggregate after applying the event.
This method returns the latest schema version that the Aggregator can process. The default implementation returns 0.
default int schemaVersion() {
return 0;
}Returns:
- The current schema version, represented as an integer (default is 0).
This method is designed for event schema migration. It takes an event represented as a JsonObject and the target schema version, then returns the transformed event if supported. The default implementation will throw an UnknownEvent exception.
default E migrate(int schemaVersion, JsonObject event) {
// throws UnknownEvent
}Parameters:
-
schemaVersion: The target schema version to which the event should be migrated. -
event: The event as aJsonObjectto be migrated.
Returns:
- A migrated event, if migration is supported.
Exceptions:
- Throws an
UnknownEventexception if migration is not supported.
This method returns the type of event that the aggregator is designed to handle.
String eventType();A typical Aggregator might look like:
public class UserAggregator implements Aggregator<UserAggregate, UserEvent> {
@Override
public UserAggregate apply(UserAggregate aggregate, UserEvent event) {
// apply event logic and return updated aggregate
}
@Override
public String eventType() {
return "UserEvent";
}
}Here, UserAggregator implements the Aggregator interface and is set to handle UserEvent events and UserAggregate aggregates.
By adhering to this updated interface, your custom aggregators will be compatible with the advanced features of es4j, including event schema migration.