All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.serialized.client.aggregate.AggregateFactory Maven / Gradle / Ivy

There is a newer version: 7.8.0
Show newest version
package io.serialized.client.aggregate;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import static java.util.Arrays.asList;

public class AggregateFactory {

  private final StateBuilder stateBuilder;
  private final Function initializer;

  public AggregateFactory(Function initializer, StateBuilder stateBuilder) {
    this.stateBuilder = stateBuilder;
    this.initializer = initializer;
  }

  public A fromCommands(List> commands) {
    List> events = new ArrayList<>();
    for (Command command : commands) {
      T aggregateState = stateBuilder.buildState(events);
      A a = initializer.apply(aggregateState);
      List> apply = command.apply(a);
      events.addAll(apply);
    }
    T lastState = stateBuilder.buildState(events);
    return initializer.apply(lastState);
  }

  /**
   * Builds an aggregate root instance from a number of commands, useful for scenario testing.
   *
   * @param commands the commands to apply to build the aggregate root
   * @return aggregate root with the state from applying all commands in sequence.
   */
  @SafeVarargs
  public final A fromCommands(Command... commands) {
    return fromCommands(asList(commands));
  }

  public static  AggregateFactory newFactory(Function initializer, StateBuilder stateBuilder) {
    return new AggregateFactory<>(initializer, stateBuilder);
  }

}






© 2015 - 2025 Weber Informatics LLC | Privacy Policy