completeWith
Signature
Description
Uses the marshaller for a given type to produce a completion function that is passed to its inner route. You can use it to decouple marshaller resolution from request completion.
The completeWith
directive works in conjuction with instanceOf
and spray.httpx.marshalling
to convert higher-level (object) structure into some lower-level serialized "wire format".
The marshalling documentation explains this process in detail.
This directive simplifies exposing types to clients via a route while providing some
form of access to the current context.
completeWith
is similar to handleWith
. The main difference is with completeWith
you must eventually call
the completion function generated by completeWith
. handleWith
will automatically call complete
when the
handleWith
function returns.
Examples
The following example uses spray-json
to marshall a simple Person
class to a json
response. It utilizes SprayJsonSupport
via the PersonJsonSupport
object as the in-scope
unmarshaller.
object PersonJsonSupport extends DefaultJsonProtocol with SprayJsonSupport {
implicit val PortofolioFormats = jsonFormat2(Person)
}
case class Person(name: String, favoriteNumber: Int)
The findPerson
takes an argument of type Person => Unit
which is generated by the completeWith
call. We can handle any logic we want in findPerson
and call our completion function to
complete the request.
import PersonJsonSupport._
val findPerson = (f: Person => Unit) => {
//... some processing logic...
//complete the request
f(Person("Jane", 42))
}
val route = get {
completeWith(instanceOf[Person]) { completionFunction => findPerson(completionFunction) }
}
// tests:
Get("/") ~> route ~> check {
mediaType shouldEqual `application/json`
responseAs[String] should include(""""name":"Jane"""")
responseAs[String] should include(""""favoriteNumber":42""")
}
Contents