I'm working with Spray+Akka (I want to say "Framework" but they want to be called as a "Library"). I get a REST call and I return a response. However, I find my processing a bit repetitive. Here are the two blocks when I received POST
request from two APIs:
post {
entity(as[JObject]) { company =>
if (AuthInfo.rejectedOrNot) {
val response = (secCompanyActor ? jObjectFromWeb(company))
.mapTo[TransOk]
.map(result => result.succeedOrNot match {
case true => (OK, "transaction successful")
case false => (BadRequest, result.errorMessage)
}).recover { case _ => (BadRequest, "An error has occurred! We will fix this")}
complete(response)
} else {
complete(Unauthorized, "Please use HTTP header to authorize this command.")
}
}
The other block is strikingly similar, but the only difference is instead of sending jObjectFromWeb(...)
, I have to send this message: jObjectFromComputer(...)
.
I wanted to create a function where I pass in the message and then send the message from that function, but Akka's messages aren't TYPED! I understand the philosophy from untyped message and I'm not arguing for anything, but I want a nice solution. Yes, one solution is that I pass in a string like sendMessageToActor(actor, "jObjectFromWeb")
and in the actual function, I use a pattern match to send the corresponding message.
But it is a bit ugly and not very modular (what if I have 10 messages to send?).
Is there any way to do this? I'm not quite familar with Java's reflection, but it would be very nice if I can just find the message case class/object through a string.
This is my Akka actor side of implementation:
class SECCompanyActor extends Actor with ActorLogging {
import com.mturk.tasks.SECcompany.SECCompanyProtocol._
def receive = {
case jObjectFromCasper(jObject) =>
//Do some logic
sender ! TransOk(result._1, result._2, result._3)
case jObjectFromWeb(jObject) =>
// Do some other logic
sender ! TransOk(result._1, result._2, result._3)
}
Here is my Akka message:
object SECCompanyProtocol {
case class jObjectFromCasper(jObject: JObject)
case class TransOk(company: Option[Company.Company], succeedOrNot: Boolean, errorMessage: Option[String])
case class jObjectFromWeb(jObject: JObject)
}