Skip to content

Aggregators

Reef3rm4n edited this page Aug 29, 2023 · 2 revisions

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.

Interface Definition

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
}

Method Definitions

apply

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.

schemaVersion

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).

migrate

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 a JsonObject to be migrated.

Returns:

  • A migrated event, if migration is supported.

Exceptions:

  • Throws an UnknownEvent exception if migration is not supported.

eventType

This method returns the type of event that the aggregator is designed to handle.

String eventType();

Example Implementation

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.

Clone this wiki locally