1

我正在尝试将精炼类型用于案例类,但无法弄清楚编码器将如何实际工作。对于 json 解析,circe 与 https4s 库一起使用。

  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:(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]

最坏的情况是我需要定义自己的解码器并解析它。但是,如果有任何其他可以进一步简化的方法会很好。

4

1 回答 1

2
type NameT = String Refined NonEmptyString

是错的。将其替换为

type NameT = String Refined NonEmpty

否则NonEmptyString已经String Refined NonEmptyNameT你做Refined两次,这是错误的。

或者你可以定义只是

type NameT = NonEmptyString

不要忘记进口

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
于 2020-06-08T00:22:00.357 回答