Created
December 29, 2015 18:20
-
-
Save DiegoRam/8ec11bc987947dd317b1 to your computer and use it in GitHub Desktop.
Spray example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package api | |
import akka.actor.ActorSystem | |
import core.DefaultTimeout | |
import core.auth.authentication | |
import domain.User | |
import service.{ DeleteUser, GetUserById, SaveUser, UserFormat } | |
import spray.routing.Directives | |
import akka.pattern.ask | |
import spray.http.StatusCodes._ | |
import authentication._ | |
import scala.util.{ Success, Failure } | |
class UserApi(implicit val actorSystem: ActorSystem) extends Directives with DefaultTimeout with UserFormat { | |
import scala.concurrent.ExecutionContext.Implicits.global | |
val userActor = actorSystem.actorSelection("/user/application/user") | |
val path = "users" | |
val route = | |
path(path) { | |
post { | |
respondWithStatus(Created) { | |
handleWith { user: User => | |
(userActor ? SaveUser(user)).mapTo[User] | |
} | |
} | |
} | |
} ~ | |
path(path / IntNumber) { id => | |
authenticate(validToken) { authInfo => | |
get { | |
onComplete((userActor ? GetUserById(id)).mapTo[Option[User]]) { | |
case Success(v) => v match { | |
case Some(user) => complete(user) | |
case None => complete(NotFound) | |
} | |
case Failure(ex) => complete(InternalServerError, s"An error occurred: ${ex.getMessage}") | |
} | |
} ~ | |
delete { | |
complete { | |
(userActor ? DeleteUser(id)) map { | |
case true => OK | |
case false => BadRequest | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment