scalacircehttp4srefined

decoder for refined type when using circe with Http4s


I am trying to use refined types for a case class but couldn't figure out how the encoder will actually work. For json parsing circe is used with https4s library.

  type AgeT = Int Refined Interval.ClosedOpen[0,100]
  type NameT = String Refined NonEmptyString
  case class Person(name: NameT,age: AgeT)
  object Person  {
    implicit val encoder: Encoder[Person] =  deriveEncoder[Person]
    implicit val decoder: Decoder[Person] =  deriveDecoder[Person]
  }

  implicit val decoder = jsonOf[IO,Person]
  val jsonWithValidationService = HttpRoutes.of[IO] {
    case req @ POST -> Root / "jsonBody" =>
        for {
          c <- req.as[Person]
          res <-Ok(c.asJson)
        } yield res
  }.orNotFound

Error

Error:(61, 59) could not find Lazy implicit value of type io.circe.generic.decoding.DerivedDecoder[server.Routes.Person]
    implicit val decoder: Decoder[Person] =  deriveDecoder[Person]

Worst case I need to define my own decoder and parse it. But if there's any other way that can simplify further would be nice.


Solution

  • type NameT = String Refined NonEmptyString
    

    is wrong. Replace it with

    type NameT = String Refined NonEmpty
    

    Otherwise NonEmptyString is already String Refined NonEmpty and in NameT you do Refined twice, which is wrong.

    Or you can define just

    type NameT = NonEmptyString
    

    Don't forget imports

    import cats.effect.IO
    import eu.timepit.refined.api.Refined
    import eu.timepit.refined.numeric.Interval
    import eu.timepit.refined.collection.NonEmpty
    import eu.timepit.refined.types.string.NonEmptyString
    import io.circe.{Decoder, Encoder}
    import io.circe.generic.semiauto._
    import io.circe.syntax._
    import io.circe.refined._
    import org.http4s.circe._
    import org.http4s.dsl.io._
    import org.http4s.implicits._
    import org.http4s.HttpRoutes