Created
April 11, 2017 19:00
-
-
Save dgouyette/2f7003e3e27174b8d1f3127341fcfe5d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import jto.validation.{Rule, VA} | |
import shapeless.Poly1 | |
import shapeless._ | |
import labelled.{FieldType, field} | |
object validator extends Poly1 { | |
implicit def list[H <: Validator[Int], T <: HList](implicit witness: Witness.Aux[H]) : Case.Aux[FieldType[H, String]::T, HList] = at(l => validator(l.head) :: HNil ) | |
implicit def kvString[K <: Validator[String]](implicit witness: Witness.Aux[K]): Case.Aux[FieldType[K, String], VA[String]] = at(in => { | |
getValidatorByType(in).rules.validate(getFieldValue(in)) | |
}) | |
implicit def kvInt[K <: Validator[Int]](implicit witness: Witness.Aux[K]): Case.Aux[FieldType[K, String], VA[Int]] = at(in => { | |
getValidatorByType(in).rules.validate(getFieldValue(in)) | |
}) | |
implicit def kvBoolean[K <: Validator[Boolean]](implicit witness: Witness.Aux[K]): Case.Aux[FieldType[K, String], VA[Boolean]] = at(in => { | |
getValidatorByType(in).rules.validate(getFieldValue(in)) | |
}) | |
} | |
trait Validator[In] { | |
def rules: Rule[String, In] | |
} | |
object EmailValidator extends Validator[String] { | |
val rules: Rule[String, String] = Rules.email |+| Rules.notEmpty | |
} | |
object IntValidator extends Validator[Int] { | |
val rules: Rule[String, Int] = Rules.intR | |
} | |
object BoolValidator extends Validator[Boolean] { | |
val rules: Rule[String, Boolean] = Rules.booleanR | |
} | |
type Email = FieldType[EmailValidator.type, String] | |
def email(value: String): FieldType[EmailValidator.type, String] = field[EmailValidator.type](value) | |
type IntString = FieldType[IntValidator.type, String] | |
def intString(value: String): FieldType[IntValidator.type, String] = field[IntValidator.type](value) | |
type BoolString = FieldType[BoolValidator.type, String] | |
def boolString(value: String): FieldType[BoolValidator.type, String] = field[BoolValidator.type](value) | |
def getValidatorByType[K](value: FieldType[K, String])(implicit witness: Witness.Aux[K]): K = witness.value | |
def getFieldValue[K](value: FieldType[K, String]): String = value | |
case class Row(email: Email, age: IntString, cgu: BoolString) | |
validator(intString("a") :: intString("1") :: HNil) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment