Last active
June 20, 2019 15:50
-
-
Save roshane/39d764643726d51d54ff0d7e3bc0f355 to your computer and use it in GitHub Desktop.
validation engine template
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
import scala.concurrent.Future | |
import scala.concurrent.ExecutionContext.Implicits.global | |
trait Request | |
case class AdhocCreateRequest(name: String) extends Request | |
case class RegularCreateRequest(name: String) extends Request | |
class Repository { | |
def doSomething = println("hello from repository") | |
} | |
abstract class ValidationRule[T] { | |
def isSupported(t: T): Boolean | |
def validate(t: T): Future[Unit] | |
} | |
class RootValidationRule[T](val maybeSuccessor: Option[ValidationRule[T]]) | |
extends ValidationRule[T] { | |
def isSupported(t: T): Boolean = true | |
def validate(t: T): Future[Unit] = maybeSuccessor.fold(Future.unit)(_.validate(t)) | |
} | |
class FieldValidationRule[T](val maybeSuccessor: Option[ValidationRule[T]]) | |
extends ValidationRule[T] { | |
def isSupported(t: T): Boolean = t.getClass() == classOf[AdhocCreateRequest] | |
def validate(t: T): Future[Unit] = isSupported(t) match { | |
case true => | |
println(s"validating request $t") | |
val request = t.asInstanceOf[AdhocCreateRequest] | |
Future {} | |
case _ => maybeSuccessor.fold(Future.unit)(_.validate(t)) | |
} | |
} | |
class OverlapValidationRule[T](val maybeSuccessor: Option[ValidationRule[T]])(implicit repository: Repository) | |
extends ValidationRule[T] { | |
def isSupported(t: T): Boolean = t.getClass() == classOf[RegularCreateRequest] | |
def validate(t: T): Future[Unit] = isSupported(t) match { | |
case true => | |
println(s"validating request $t") | |
val request = t.asInstanceOf[RegularCreateRequest] | |
Future { | |
repository.doSomething | |
throw new Exception("Invalid request is overlapping") | |
} | |
case _ => | |
println(s"$t skipping ${classOf[OverlapValidationRule[T]]}") | |
maybeSuccessor.fold(Future.unit)(_.validate(t)) | |
} | |
} | |
object ValidationEngine extends App { | |
implicit val repository = new Repository | |
val fieldValidationRule = new FieldValidationRule[Request](None) | |
val overlapValidationRule = new OverlapValidationRule[Request](Some(fieldValidationRule)) | |
val rootValidationRule = new RootValidationRule(Some(overlapValidationRule)) | |
val adhocCreate = AdhocCreateRequest("create adhoc schedule") | |
val regularCreate = RegularCreateRequest("create regular schedule") | |
rootValidationRule.validate(adhocCreate) | |
rootValidationRule.validate(regularCreate) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment