-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
26 additions
and
2 deletions.
There are no files selected for viewing
28 changes: 26 additions & 2 deletions
28
schema/src/main/scala-3/net/reactivecore/cjs/validator/impl/CombinedValidationProvider.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 |
---|---|---|
@@ -1,10 +1,34 @@ | ||
package net.reactivecore.cjs.validator.impl | ||
|
||
import net.reactivecore.cjs.validator.{ValidationProvider, Validator} | ||
import scala.deriving.Mirror | ||
import scala.compiletime.{erasedValue, summonInline} | ||
import net.reactivecore.cjs.SchemaOrigin | ||
|
||
/** Helper trait for synthetic validation provider for case classes */ | ||
trait CombinedValidationProvider[T] extends ValidationProvider[T] | ||
|
||
object CombinedValidationProvider { | ||
implicit def provide[T]: CombinedValidationProvider[T] = ??? | ||
} | ||
implicit inline def provide[T <: Product](using m: Mirror.ProductOf[T]): CombinedValidationProvider[T] = { | ||
val tupleVariant = provideForTuple[m.MirroredElemTypes] | ||
new CombinedValidationProvider[T] { | ||
override def apply(origin: SchemaOrigin, restriction: T): Validator = { | ||
val validators = restriction.productIterator.zip(tupleVariant).map { case (field, subValidationProvider) => | ||
subValidationProvider(origin, field) | ||
} | ||
Validator.sequence(validators.toSeq: _*) | ||
} | ||
} | ||
} | ||
|
||
private inline def provideForTuple[T <: Tuple]: List[ValidationProvider[Any]] = { | ||
inline erasedValue[T] match { | ||
case _: EmptyTuple => Nil | ||
case _: (t *: ts) => | ||
val first = summonInline[ValidationProvider[t]].asInstanceOf[ValidationProvider[Any]] | ||
val last = provideForTuple[ts] | ||
first :: last | ||
} | ||
} | ||
|
||
} |