2

假设我们有一个命令AddUser

case class AddUser(username: String, password: String)

在持久化事件之前验证此命令的最佳方法是什么?例如,以这样的方式进行操作似乎有点混乱。

override def receiveCommand: Receive = {
    case AddUser(username, password) =>
      if (username.trim.length > 25) {
        sender() ! UsernameTooLong
      } else if (password.trim.length > 25) {
        sender() ! PasswordTooLong
      } else {
        persist(UserAdded(User(username, password))) {
          userAdded =>
            sender() ! userAdded
        }
      }
}
4

1 回答 1

2

您需要使用接收管道模式:http ://doc.akka.io/docs/akka/2.4.1/contrib/receive-pipeline.html

你可以这样做:

trait AuthenticatedUser { this: ReceivePipeline =>
   pipelineInner {
    case msg@AddUser(username, password) => 
     if (username.trim.length > 25) {
        sender() ! UsernameTooLong
     } else if (password.trim.length > 25) {
        sender() ! PasswordTooLong
     } else {
       Inner(msg)
     }
   case msg => Inner(msg)
   }
}

class UserActor extends Actor with ReceivePipeline with AuthenticatedUser {

 def receive = {
   case AddUser(username, password) =>
    persist(UserAdded(User(username, password))) {
          userAdded =>
            sender() ! userAdded
        }
  }
}

PS:我没有编译和测试过这段代码,但我相信它会起作用,如果有任何问题,请告诉我。

于 2016-05-31T10:30:57.897 回答