Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
63 lines (48 sloc) 1.65 KB
package com.netaporter.routing
import akka.actor.SupervisorStrategy.Stop
import akka.actor.{OneForOneStrategy, _}
import com.netaporter._
import com.netaporter.routing.PerRequest._
import org.json4s.DefaultFormats
import spray.http.StatusCode
import spray.http.StatusCodes._
import spray.httpx.Json4sSupport
import spray.routing.RequestContext
import scala.concurrent.duration._
trait PerRequest extends Actor with Json4sSupport {
import context._
val json4sFormats = DefaultFormats
def r: RequestContext
def target: ActorRef
def message: RestMessage
setReceiveTimeout(2.seconds)
target ! message
def receive = {
case res: RestMessage => complete(OK, res)
case v: Validation => complete(BadRequest, v)
case ReceiveTimeout => complete(GatewayTimeout, Error("Request timeout"))
}
def complete[T <: AnyRef](status: StatusCode, obj: T) = {
r.complete(status, obj)
stop(self)
}
override val supervisorStrategy =
OneForOneStrategy() {
case e =>
complete(InternalServerError, Error(e.getMessage))
Stop
}
}
object PerRequest {
case class WithActorRef(r: RequestContext, target: ActorRef, message: RestMessage) extends PerRequest
case class WithProps(r: RequestContext, props: Props, message: RestMessage) extends PerRequest {
lazy val target = context.actorOf(props)
}
}
trait PerRequestCreator {
this: Actor =>
def perRequest(r: RequestContext, target: ActorRef, message: RestMessage) =
context.actorOf(Props(new WithActorRef(r, target, message)))
def perRequest(r: RequestContext, props: Props, message: RestMessage) =
context.actorOf(Props(new WithProps(r, props, message)))
}
You can’t perform that action at this time.