诺 铁
诺 铁

Reputation: 615

how to combine frequently used path pattern using "&" in spray

I am using spray to expose restful service. since there are common pattern in most service, so I using "&" to create alias for it. like following:

def getPath(path1: String) = path(path1) & get & detach() & complete

this code is written inside a trait MyService extends HttpService with Json4sSupport , if you try to compile it separately, you may have to write like this

def getPath(path1: String)(implicit ec: ExecutionContext) = path(path1) & spray.routing.Directives.get & detach() & complete

and use it is in route is easy:

~ getPath("person2") { xxx }  
//works as
//path("person1") {
//        get {
//          detach() {
//            complete {
//              println("receiving request /person1")
//              something
//            }
//          }
//        }
//      }

but I don't know how to create same alias for post:

path("account" / "transaction") {
        post {
          entity(as[TransferRequest]) { transferReq =>
            detach() {
              complete {
                //doing transfer
              }
            }
          }
        }
      }

I've tried

def postPath[T](path1: String) = path(path1) & post & entity(as[T]) & detach() & complete

but doesn't work , no where to get the "transferReq" parameter. how should I define to get what I want?

Upvotes: 2

Views: 124

Answers (1)

xiefei
xiefei

Reputation: 6599

complete is not a composable directive, take it out and you are all good. Try this

def postPath[T](path1: String)(implicit um:FromRequestUnmarshaller[T], ec: ExecutionContext): Directive1[T] = 
    path(path1) & post & entity(as[T]) & detach(())

then in your call site, use it like this

import concurrent.ExecutionContext.Implicits.global

postPath[String]("123").apply { s =>
  complete (s + "abc")
}

Upvotes: 2

Related Questions