-
Notifications
You must be signed in to change notification settings - Fork 422
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for refined #405
Merged
adamw
merged 5 commits into
softwaremill:master
from
strokyl:add_codec_support_for_refined
Feb 6, 2020
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
File renamed without changes.
66 changes: 66 additions & 0 deletions
66
integration/refined/src/main/scala/sttp/tapir/codec/refined/TapirCodecRefined.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package sttp.tapir.codec.refined | ||
|
||
import sttp.tapir._ | ||
import eu.timepit.refined.api.{Max, Refined, Validate} | ||
import eu.timepit.refined.collection.NonEmpty | ||
import eu.timepit.refined.refineV | ||
import eu.timepit.refined.string.MatchesRegex | ||
import eu.timepit.refined.numeric.{Greater, GreaterEqual, Less, LessEqual} | ||
import shapeless.Witness | ||
|
||
import scala.reflect.ClassTag | ||
|
||
trait RefinedValidatorTranslation[V, P] { | ||
def tapirValidator: Validator[V] | ||
def listError(value: V, refinedErrorMessage: String): List[ValidationError[_]] | ||
} | ||
|
||
object RefinedValidatorTranslation { | ||
def fromPrimitiveValidator[V, P](validator: Validator.Primitive[V]) = new RefinedValidatorTranslation[V, P] { | ||
override def tapirValidator: Validator[V] = validator | ||
override def listError(value: V, refinedErrorMessage: String): List[ValidationError[_]] = List(ValidationError[V](validator, value)) | ||
} | ||
} | ||
|
||
trait TapirCodecRefined extends ImplicitGenericRefinedValidator { | ||
implicit def codecForRefined[V, P, CF <: CodecFormat, R](implicit tm: Codec[V, CF, R], refinedValidator: Validate[V, P], refinedValidatorTranslation: RefinedValidatorTranslation[V, P]): Codec[V Refined P, CF, R] = { | ||
implicitly[Codec[V, CF, R]] | ||
.validate(refinedValidatorTranslation.tapirValidator) // in reality if this validator has to fail, it will fail before in mapDecode while trying to construct refined type | ||
.mapDecode { v: V => | ||
refineV[P](v) match { | ||
case Right(refined) => DecodeResult.Value(refined) | ||
case Left(errorMessage) => { | ||
DecodeResult.InvalidValue(refinedValidatorTranslation.listError(v, errorMessage)) | ||
} | ||
} | ||
}(_.value) | ||
} | ||
|
||
implicit val nonEmptyStringRefinedTranslator: RefinedValidatorTranslation[String, NonEmpty] = | ||
RefinedValidatorTranslation.fromPrimitiveValidator[String, NonEmpty](Validator.minLength(1)) | ||
|
||
implicit def matchesRegexRefinedTranslator[S <: String](implicit ws: Witness.Aux[S]): RefinedValidatorTranslation[String, MatchesRegex[S]] = | ||
RefinedValidatorTranslation.fromPrimitiveValidator(Validator.pattern(ws.value)) | ||
|
||
implicit def lessRefinedTranslator[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): RefinedValidatorTranslation[N, Less[NM]] = | ||
RefinedValidatorTranslation.fromPrimitiveValidator(Validator.max(ws.value, exclusive = true)) | ||
|
||
implicit def lessEqualRefinedTranslator[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): RefinedValidatorTranslation[N, LessEqual[NM]] = | ||
RefinedValidatorTranslation.fromPrimitiveValidator(Validator.max(ws.value, exclusive = false)) | ||
|
||
implicit def maxRefinedTranslator[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): RefinedValidatorTranslation[N, Greater[NM]] = | ||
RefinedValidatorTranslation.fromPrimitiveValidator(Validator.min(ws.value, exclusive = true)) | ||
|
||
implicit def maxEqualRefinedTranslator[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): RefinedValidatorTranslation[N, GreaterEqual[NM]] = | ||
RefinedValidatorTranslation.fromPrimitiveValidator(Validator.min(ws.value, exclusive = false)) | ||
} | ||
|
||
trait ImplicitGenericRefinedValidator { | ||
implicit def genericRefinedValidatorTranslation[V, P: ClassTag](implicit refinedValidator: Validate[V, P]): RefinedValidatorTranslation[V, P] = new RefinedValidatorTranslation[V, P] { | ||
override val tapirValidator: Validator.Custom[V] = Validator.Custom( | ||
refinedValidator.isValid(_), | ||
implicitly[ClassTag[P]].runtimeClass.toString) //for the moment there is no way to get a human description of a predicate/validator without having a concrete value to run it | ||
|
||
override def listError(value: V, refinedErrorMessage: String): List[ValidationError[_]] = List(ValidationError[V](tapirValidator.copy(message = refinedErrorMessage), value)) | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
integration/refined/src/main/scala/sttp/tapir/codec/refined/package.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
package sttp.tapir.codec | ||
|
||
package object refined extends TapirCodecRefined |
79 changes: 79 additions & 0 deletions
79
integration/refined/src/test/scala/sttp/tapir/codec/refined/TapirCodecRefinedTest.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
package sttp.tapir.codec.refined | ||
|
||
import eu.timepit.refined.api.{Max, Refined} | ||
import eu.timepit.refined.collection.NonEmpty | ||
import eu.timepit.refined.numeric.{Greater, GreaterEqual, Less, LessEqual} | ||
import eu.timepit.refined.string.{IPv4, MatchesRegex} | ||
import eu.timepit.refined.{W, refineMV, refineV} | ||
import eu.timepit.refined.types.string.NonEmptyString | ||
import org.scalatest.{FlatSpec, Matchers} | ||
import sttp.tapir.Codec.PlainCodec | ||
import sttp.tapir.{DecodeResult, ValidationError, Validator} | ||
|
||
class TapirCodecRefinedTest extends FlatSpec with Matchers with TapirCodecRefined { | ||
|
||
val nonEmptyStringCodec = implicitly[PlainCodec[NonEmptyString]] | ||
|
||
|
||
"Generated codec" should "return DecodResult.Invalid if subtype can't be refined with correct tapir validator if available" in { | ||
val expectedValidator: Validator[String] = Validator.minLength(1) | ||
nonEmptyStringCodec.decode("") should matchPattern{case DecodeResult.InvalidValue(List(ValidationError(validator, "", _))) if validator == expectedValidator=>} | ||
} | ||
|
||
it should "correctly delegate to raw parser and refine it" in { | ||
nonEmptyStringCodec.decode("vive le fromage") shouldBe DecodeResult.Value(refineMV[NonEmpty]("vive le fromage")) | ||
} | ||
|
||
it should "return DecodResult.Invalid if subtype can't be refined with derived tapir validator if non tapir validator available" in { | ||
type IPString = String Refined IPv4 | ||
val IPStringCodec = implicitly[PlainCodec[IPString]] | ||
|
||
val expectedMsg = refineV[IPv4]("192.168.0.1000").left.get | ||
IPStringCodec.decode("192.168.0.1000") should matchPattern{case DecodeResult.InvalidValue(List(ValidationError(Validator.Custom(_, `expectedMsg`), "192.168.0.1000", _)))=>} | ||
} | ||
|
||
"Generated codec for MatchesRegex" should "use tapir Validator.Pattern" in { | ||
type VariableConstraint = MatchesRegex[W.`"[a-zA-Z][-a-zA-Z0-9_]*"`.T] | ||
type VariableString = String Refined VariableConstraint | ||
val identifierCodec = implicitly[PlainCodec[VariableString]] | ||
|
||
val expectedValidator: Validator[String] = Validator.pattern("[a-zA-Z][-a-zA-Z0-9_]*") | ||
identifierCodec.decode("-bad") should matchPattern{case DecodeResult.InvalidValue(List(ValidationError(validator, "-bad", _))) if validator == expectedValidator=>} | ||
} | ||
|
||
"Generated codec for Less" should "use tapir Validator.drMax" in { | ||
type IntConstraint = Less[W.`3`.T] | ||
type LimitedInt = Int Refined IntConstraint | ||
val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] | ||
|
||
val expectedValidator: Validator[Int] = Validator.max(3, exclusive = true) | ||
limitedIntCodec.decode("3") should matchPattern{case DecodeResult.InvalidValue(List(ValidationError(validator, 3, _))) if validator == expectedValidator=>} | ||
} | ||
|
||
"Generated codec for LessEqual" should "use tapir Validator.drMax" in { | ||
type IntConstraint = LessEqual[W.`3`.T] | ||
type LimitedInt = Int Refined IntConstraint | ||
val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] | ||
|
||
val expectedValidator: Validator[Int] = Validator.max(3, exclusive = false) | ||
limitedIntCodec.decode("4") should matchPattern{case DecodeResult.InvalidValue(List(ValidationError(validator, 4, _))) if validator == expectedValidator=>} | ||
} | ||
|
||
"Generated codec for Max" should "use tapir Validator.drMax" in { | ||
type IntConstraint = Greater[W.`3`.T] | ||
type LimitedInt = Int Refined IntConstraint | ||
val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] | ||
|
||
val expectedValidator: Validator[Int] = Validator.min(3, exclusive = true) | ||
limitedIntCodec.decode("3") should matchPattern{case DecodeResult.InvalidValue(List(ValidationError(validator, 3, _))) if validator == expectedValidator=>} | ||
} | ||
|
||
"Generated codec for MaxEqual" should "use tapir Validator.drMax" in { | ||
type IntConstraint = GreaterEqual[W.`3`.T] | ||
type LimitedInt = Int Refined IntConstraint | ||
val limitedIntCodec = implicitly[PlainCodec[LimitedInt]] | ||
|
||
val expectedValidator: Validator[Int] = Validator.min(3, exclusive = false) | ||
limitedIntCodec.decode("2") should matchPattern{case DecodeResult.InvalidValue(List(ValidationError(validator, 2, _))) if validator == expectedValidator=>} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 I like the last line :)