Skip to content

Instantly share code, notes, and snippets.

@aludwiko
Created July 27, 2018 12:38
Show Gist options
  • Save aludwiko/0ecef07d77de0ebc3969ff271797f432 to your computer and use it in GitHub Desktop.
Save aludwiko/0ecef07d77de0ebc3969ff271797f432 to your computer and use it in GitHub Desktop.
final case class User private[domain] (userId: UserId, createdAt: Instant, name: String, email: Email) {
def applyEvent(userEvent: UserEvent): Try[User] = userEvent match {
case _: UserCreated => Failure(new IllegalStateException("User already created. Event cannot be applied."))
case event: NameUpdated => Success(copy(name = event.newName))
case event: EmailUpdated => Success(copy(email = event.newEmail))
}
def process(userCommand: UserCommand): Try[List[UserEvent]] = userCommand match {
case _: CreateUser => Failure(new IllegalStateException("User already created. Command cannot be processed."))
case command: UpdateName => updateName(command)
case command: UpdateEmail => updateEmail(command)
}
def updateName(command: UpdateName): Try[List[UserEvent]] = {
//complex business logic that might failed
Success(List(command.toNameUpdated()))
}
def updateEmail(command: UpdateEmail): Try[List[UserEvent]] = {
//complex business logic that might failed
Success(List(command.toEmailUpdated()))
}
}
object User {
def from(userCreated: UserCreated): User =
User(userCreated.userId, userCreated.createdAt, userCreated.name, userCreated.email)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment