SHARE
TWEET

Json decoder for custom extensions

mitrakov Mar 26th, 2019 (edited) 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // here we add custom extension to the web request so that it will have the following header:
  2. // "Accept: application/json;profile=my-profile"
  3.  
  4. // build.sbt
  5. libraryDependencies ++= Seq(
  6.   "org.slf4j" % "slf4j-nop" % "1.7.21",
  7.   "io.circe" %% "circe-generic" % "0.10.0",
  8.   "org.http4s" %% "http4s-circe" % "0.18.23",
  9.   "org.http4s" %% "http4s-blaze-client" % "0.18.23"
  10. )
  11.  
  12. // Hello.scala:
  13. import scala.language.higherKinds
  14. import cats.Monad
  15. import cats.effect.{Effect, IO}
  16. import io.circe.Decoder
  17. import org.http4s._
  18. import org.http4s.client.blaze.Http1Client
  19. import org.http4s.circe._
  20. import io.circe.generic.semiauto._
  21.  
  22. object Hello extends App {
  23.   case class User(name: String)
  24.   implicit val userDecoder: Decoder[User] = deriveDecoder
  25.  
  26.   def jsonExtensionsDecoder[F[_]: Monad: Effect, A](extensions: Map[String, String])
  27.                                                    (implicit decoder: Decoder[A]): EntityDecoder[F, A] = {
  28.     new EntityDecoder[F, A] {
  29.       override def decode(msg: Message[F], strict: Boolean): DecodeResult[F, A] = jsonOf[F, A].decode(msg, strict)
  30.       override def consumes: Set[MediaRange] = Set(MediaType.`application/json`.withExtensions(extensions))
  31.     }
  32.   }
  33.  
  34.   val httpClient = Http1Client[IO]().unsafeRunSync()
  35.   val header = Header("x", "y")
  36.   val usersIO = httpClient.expect(Request[IO](uri = Uri(path = "https://google.com"), headers = Headers(header)))(
  37.     jsonExtensionsDecoder[IO, Seq[User]](Map("profile" -> "my-profile"))
  38.   )
  39.   val users = usersIO.unsafeRunSync()
  40.  
  41.   println(s"Users: $users")
  42. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top