简体   繁体   English

使用 circe 和 Http4s 时精炼类型的解码器

[英]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.我正在尝试对案例 class 使用精炼类型,但无法弄清楚编码器将如何实际工作。 For json parsing circe is used with https4s library.对于 json,解析循环与 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错误

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.但是,如果有任何其他可以进一步简化的方法会很好。

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.否则NonEmptyString已经是String Refined NonEmpty并且在NameT你做Refined两次,这是错误的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM