Last active
January 7, 2022 15:11
-
-
Save darkfrog26/d8efb1db7b17319a532bc777cbdce8d3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package live.prepared | |
import cats.data.EitherT | |
import cats.effect._ | |
import cats.implicits._ | |
import fabric.parse.Json | |
import fabric.rw._ | |
import fs2.Chunk | |
import org.http4s._ | |
import org.http4s.dsl.Http4sDsl | |
import org.http4s.ember.server.EmberServerBuilder | |
case class User(name: String) | |
object User { | |
implicit val rw: ReaderWriter[User] = ccRW | |
} | |
case class Hello(greeting: String) | |
object Hello { | |
implicit val rw: ReaderWriter[Hello] = ccRW | |
} | |
object JSONTest extends IOApp with Http4sDsl[IO] { | |
override def run(args: List[String]): IO[ExitCode] = { | |
EmberServerBuilder | |
.default[IO] | |
.withHttpApp(jsonApp.orNotFound) | |
.build | |
.use(server => IO.println(server.baseUri) *> IO.never) | |
.as(ExitCode.Success) | |
} | |
implicit val decoder: EntityDecoder[IO, User] = FabricEntitySupport.decoder[User] | |
implicit val encoder: EntityEncoder[IO, Hello] = FabricEntitySupport.encoder[Hello] | |
val jsonApp: HttpRoutes[IO] = HttpRoutes.of[IO] { | |
case request @ POST -> Root / "hello" => for { | |
// Decode a User request | |
user <- request.as[User] | |
// Encode a hello response | |
resp <- Ok(Hello(user.name)) | |
} yield resp | |
} | |
} | |
object FabricEntitySupport { | |
def decoder[T](implicit writer: Writer[T]): EntityDecoder[IO, T] = | |
EntityDecoder.decodeBy(MediaType.application.json) { media => | |
EitherT { | |
media.as[String].map { jsonString => | |
val json = Json.parse(jsonString) | |
val t = writer.write(json) | |
t.asRight[DecodeFailure] | |
} | |
} | |
} | |
def encoder[T](implicit reader: Reader[T]): EntityEncoder[IO, T] = EntityEncoder | |
.Pure[Chunk[Byte]] | |
.contramap[T] { t => | |
val value = t.toValue | |
val string = Json.format(value) | |
val bytes = string.getBytes("UTF-8") | |
Chunk.array(bytes) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment