Instead of using TurnJsonIntoHttp in each place:
class MyEndpoint extends Endpoint[HttpRequest, HttpResponse] {
def route = {
case Method.Get -> Root / "items" ⇒
List() ! TurnJsonIntoHttp[List[MyObj]]
case Method.Get -> Root / "item" / Long(id) ⇒
GetDetail(id) ! TurnJsonIntoHttp[MyObj]
//...
}
}
==========
We could do something like:
implicit class ToJsonOps[Req, Resp](service: Service[Req, Resp]) {
def asJson(implicit encode: EncodeJson[Resp]) =
new Service[Req, HttpResponse] {
def apply(req: Req) = service(req) flatMap TurnJsonIntoHttp[Resp]
}
}
And in route:
class MyEndpoint extends Endpoint[HttpRequest, HttpResponse] {
def route = {
case Method.Get -> Root / "items" ⇒
List().asJson
case Method.Get -> Root / "item" / Long(id) ⇒
GetDetail(id).asJson
//...
}
}
Like it!
But, instead of writing
TurnJsonIntoHttp
each time, you can have JSON endpoints, likeEndpoint[HttpRequest, Json]
. And thenendpoint ! TurnJsonIntHttp[???]
.I see the point. You expose you model as simple case classes (and lists over case classes). So, you don't use an JSON backend explicitly and just converts pure object to JSON strings?