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
//...
}
}
I tried make the implicit
jsonToHttp
(that also have an implicitEncodeJson
), but it didn't work.Maybe I did something wrong, gonna try again later and submit a PR with the working solution.
Also, I think that
EncodeJson
should be contravariant, and likewise,DecodeJson
should be covariant.I'll making few tests, and probably submit another PR with this change.