/
MuxEndpoints.scala
44 lines (38 loc) · 1.39 KB
/
MuxEndpoints.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package endpoints4s
package sttp.client
import _root_.sttp.client3.{asStringAlways, Request => SRequest}
import endpoints4s.algebra.MuxRequest
/** @group interpreters
*/
trait MuxEndpoints[R[_]] extends algebra.Endpoints {
self: EndpointsWithCustomErrors[R] =>
class MuxEndpoint[Req <: algebra.MuxRequest, Resp, Transport](
request: Request[Transport],
response: Response[Transport]
) {
def apply(req: Req)(implicit
encoder: Encoder[Req, Transport],
decoder: Decoder[Transport, Resp]
): R[req.Response] = {
val sttpRequest: SRequest[String, Any] =
request(encoder.encode(req)).response(asStringAlways)
val result = self.backend.send(sttpRequest)
self.backend.responseMonad.flatMap(result) { res =>
self.backend.responseMonad.flatMap(decodeResponse(response, res)) { transport =>
decoder.decode(transport) match {
case Valid(r) =>
self.backend.responseMonad.unit(r.asInstanceOf[req.Response])
case Invalid(errors) =>
self.backend.responseMonad
.error(new Exception(errors.mkString(". ")))
}
}
}
}
}
def muxEndpoint[Req <: MuxRequest, Resp, Transport](
request: Request[Transport],
response: Response[Transport]
): MuxEndpoint[Req, Resp, Transport] =
new MuxEndpoint[Req, Resp, Transport](request, response)
}