Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//> using scala "2"
//> using lib "org.typelevel::cats-core:2.8.0"
//> using lib "eu.timepit::refined:0.10.1"
//> using lib "io.circe::circe-core:0.14.2"
//> using lib "io.circe::circe-parser:0.14.2"
//> using lib "io.circe::circe-generic:0.14.2"
//> using lib "io.circe::circe-refined:0.14.2"
import cats.data.NonEmptyList
import eu.timepit.refined.auto._
import eu.timepit.refined.api.Refined
import eu.timepit.refined.string._
import eu.timepit.refined.types.string._
import eu.timepit.refined.types.numeric._
import io.circe.generic.semiauto._
import io.circe.Codec
import io.circe.refined._
import io.circe.syntax._
import io.circe.parser._
case class OrderLine(product: NonEmptyString, quantity: PosInt)
object OrderLine {
implicit val codec: Codec[OrderLine] = deriveCodec
}
case class Order(orderId: String Refined Uuid, lines: NonEmptyList[OrderLine])
object Order {
implicit val codec: Codec[Order] = deriveCodec
}
val orderLines = NonEmptyList.of(
OrderLine("100", 10),
OrderLine("101", 5)
)
val order = Order(
"c93dd655-caca-4c99-aad8-3d91ad7a1b7e",
orderLines
)
println(order.asJson.toString)
val json = """
{
"orderId" : "c93dd655-caca-4c99-aad8-3d91ad7a1b7e",
"lines" : [
{
"product" : "100",
"quantity" : 10
},
{
"product" : "101",
"quantity" : 5
}
]
}
"""
println(decode[Order](json))
val invalidJson = """
{
"orderId" : "not-an-uuid",
"lines" : [
{
"product" : "100",
"quantity" : 10
},
{
"product" : "101",
"quantity" : 5
}
]
}
"""
println(decode[Order](invalidJson))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment