2

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.

Abhi
  • 130
  • 11

1 Answers1

4
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
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • @Abhi It compiles https://scastie.scala-lang.org/JFwpHX2sQGKKio3XGYkWbg I wrote imports. Here are dependencies: `"eu.timepit" %% "refined" % "0.9.14", "org.http4s" %% "http4s-core" % "0.21.4", "io.circe" %% "circe-core" % "0.13.0", "org.typelevel" %% "cats-effect" % "2.1.3", "io.circe" %% "circe-generic" % "0.13.0", "io.circe" %% "circe-refined" % "0.13.0", "org.typelevel" %% "cats-macros" % "2.1.1", "org.typelevel" %% "cats-kernel" % "2.1.1", "org.http4s" %% "http4s-circe" % "0.21.4", "org.http4s" %% "http4s-dsl" % "0.21.4", "org.typelevel" %% "cats-core" % "2.1.1"`. Scala 2.13.2. – Dmytro Mitin Jun 08 '20 at 09:03
  • @Abhi Do `sbt clean compile`. – Dmytro Mitin Jun 08 '20 at 09:03
  • Thanks. I checked in scastie and it worked there. So I went into my program and tried to fix some dependencies which were causing the issue. It is working now. – Abhi Jun 11 '20 at 08:53