Skip to content

Commit 4986fc4

Browse files
author
Luc DUZAN
committed
Add support for refined
1 parent 82fa3d4 commit 4986fc4

File tree

5 files changed

+53
-0
lines changed

5 files changed

+53
-0
lines changed

build.sbt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,17 @@ lazy val tapirCats: Project = (project in file("cats"))
112112
)
113113
.dependsOn(core)
114114

115+
lazy val tapirRefined: Project = (project in file("refined"))
116+
.settings(commonSettings)
117+
.settings(
118+
name := "tapir-refined",
119+
libraryDependencies ++= Seq(
120+
"eu.timepit" %% "refined" % Versions.refined,
121+
scalaTest % "test"
122+
)
123+
)
124+
.dependsOn(core)
125+
115126
// json
116127

117128
lazy val circeJson: Project = (project in file("json/circe"))

project/Versions.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ object Versions {
1515
val sprayJson = "1.3.5"
1616
val scalaCheck = "1.14.1"
1717
val scalaTest = "3.0.8"
18+
val refined = "0.9.12"
1819
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package sttp.tapir.codec.refined
2+
3+
import sttp.tapir._
4+
import eu.timepit.refined.api.{Refined, Validate}
5+
import eu.timepit.refined.refineV
6+
7+
trait TapirCodecRefined {
8+
implicit def codecForRefined[V, P, CF <: CodecFormat, R](implicit tm: Codec[V, CF, R], validator: Validate[V, P]): Codec[V Refined P, CF, R] =
9+
implicitly[Codec[V, CF, R]]
10+
.mapDecode { v: V =>
11+
refineV[P](v) match {
12+
case Right(refined) => DecodeResult.Value(refined)
13+
//TODO: exploit error
14+
case Left(_) => DecodeResult.InvalidValue(List())
15+
}
16+
}(_.value)
17+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
package sttp.tapir.codec
2+
3+
package object refined extends TapirCodecRefined
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package sttp.tapir.codec.refined
2+
3+
import eu.timepit.refined.collection.NonEmpty
4+
import eu.timepit.refined.refineMV
5+
import eu.timepit.refined.types.string.NonEmptyString
6+
import org.scalatest.{FlatSpec, Matchers}
7+
import sttp.tapir.Codec.PlainCodec
8+
import sttp.tapir.DecodeResult
9+
10+
class TapirCodecRefinedTest extends FlatSpec with Matchers with TapirCodecRefined {
11+
12+
val nonEmptyStringCodec = implicitly[PlainCodec[NonEmptyString]]
13+
14+
it should "return DecodResult.Invalid if subtype can't be refined" in {
15+
nonEmptyStringCodec.decode("") should matchPattern{case DecodeResult.InvalidValue(_) =>}
16+
}
17+
18+
it should "correctly delegate to raw parser and refine it" in {
19+
nonEmptyStringCodec.decode("vive le fromage") shouldBe DecodeResult.Value(refineMV[NonEmpty]("vive le fromage"))
20+
}
21+
}

0 commit comments

Comments
 (0)