I am trying to learn spray and understand the expected workings of Directives. I have read the following
but i don't know whether the following is considered a side-effect or I am using the library incorrectly.
Problem 1
val route = get {
println("get pong")
complete("get pong")
} ~ post {
println("post pong")
complete("post")
}
Post("/ping") ~> route ~> check {
println("response: " + responseAs[String])
}
Output:
get pong
post pong
response: post
I have some experience working with Spring Mvc where we use RequestMapping for paths/methods but the idea is if a mapping is found, only code under that mapping is executed. But from the above Spray example, even though the method is POST, code under get and post directives are both executed. I do see the response only coming from post directive and I also guess List(MethodRejection(GET)) is set from executing get directive which is cleared later by post directive.
Problem 2
say, i am developing a REST Get endpoint to return a company configuration. if a company is not found, i want to return 404 saying the passed in company id is not found. say i would make this check in multiple endpoints, what is the ideal way of writing a directive without side effects.
val route1 = get {
path("companies" / Segment){
companyId =>
onCompanyExists(companyId) {
println("do not print when company does not exist")
val company = companyRepository.get(companyId)
complete(serializer.serialize(company))
}
}
}
trait CompanyRepository{
def exists(id:Long):Boolean
def get(id:Long):Company
}
can you please suggest how to define a directive with a method 'onCompanyExists' and it would somehow make sure the print statement and the following lines do not execute if the company does not exist?