Skip to content

Commit

Permalink
Replace vals with defs
Browse files Browse the repository at this point in the history
  • Loading branch information
kubukoz committed Feb 3, 2024
1 parent 6518f84 commit 023b65d
Showing 1 changed file with 38 additions and 41 deletions.
79 changes: 38 additions & 41 deletions core/src/main/scala/respectfully/API.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ import scala.quoted.Type
import scala.quoted.quotes

trait API[Alg] {
def toRoutes: Alg => HttpApp[IO]
def toClient: (Client[IO], Uri) => Alg
def toRoutes(impl: Alg): HttpApp[IO]
def toClient(client: Client[IO], uri: Uri): Alg
}

object API {
Expand Down Expand Up @@ -303,52 +303,49 @@ object API {
new API[Alg] {
private val endpointsByName = endpoints.groupBy(_.name).fmap(_.head)

override val toClient: (Client[IO], Uri) => Alg =
(c, uri) =>
fromFunction {
new AsFunction {
override def apply[In, Out](endpointName: String, in: In): IO[Out] = {
val e = endpointsByName(endpointName).asInstanceOf[Endpoint[In, Out]]
override def toClient(c: Client[IO], uri: Uri): Alg = fromFunction {
new AsFunction {
override def apply[In, Out](endpointName: String, in: In): IO[Out] = {
val e = endpointsByName(endpointName).asInstanceOf[Endpoint[In, Out]]

given Codec[e.Out] = e.output
given Codec[e.Out] = e.output

def write(
methodName: String,
input: Json,
): Request[IO] = Request[IO](uri = uri, method = Method.POST)
.withHeaders(Header.Raw(CIString("X-Method"), methodName))
.withEntity(input)
def write(
methodName: String,
input: Json,
): Request[IO] = Request[IO](uri = uri, method = Method.POST)
.withHeaders(Header.Raw(CIString("X-Method"), methodName))
.withEntity(input)

c.expect[e.Out](write(e.name, e.input.apply(in)))
}
}
c.expect[e.Out](write(e.name, e.input.apply(in)))
}
}
}

override val toRoutes: Alg => HttpApp[IO] =
impl => {
val implFunction = asFunction(impl)

HttpApp { req =>
val methodName: String =
req
.headers
.get(CIString("X-Method"))
.getOrElse(sys.error("missing X-Method header"))
.head
.value
override def toRoutes(impl: Alg): HttpApp[IO] = {
val implFunction = asFunction(impl)

HttpApp { req =>
val methodName: String =
req
.as[Json]
.flatMap { input =>
val e = endpointsByName(methodName)

e.input
.decodeJson(input)
.liftTo[IO]
.flatMap(implFunction.apply[e.In, e.Out](e.name, _).map(e.output.apply(_)))
}
.map(Response[IO]().withEntity(_))
}
.headers
.get(CIString("X-Method"))
.getOrElse(sys.error("missing X-Method header"))
.head
.value
req
.as[Json]
.flatMap { input =>
val e = endpointsByName(methodName)

e.input
.decodeJson(input)
.liftTo[IO]
.flatMap(implFunction.apply[e.In, e.Out](e.name, _).map(e.output.apply(_)))
}
.map(Response[IO]().withEntity(_))
}
}

}

Expand Down

0 comments on commit 023b65d

Please sign in to comment.