-
-
Save srmppn/beb6b18e68a4084c7ac30342334a0993 to your computer and use it in GitHub Desktop.
Set-based consistency validation.
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
@Target(AnnotationTarget.FIELD) | |
@Retention(AnnotationRetention.RUNTIME) | |
@Constraint(validatedBy = [ConsistencyValidator::class]) | |
annotation class ConsistencyValidation( | |
val message: String = "Set-based consistency detected.", | |
val groups: Array<KClass<*>> = [], | |
val payload: Array<KClass<out Payload>> = [], | |
val name: String | |
) | |
@Component | |
class ConsistencyValidator: ConstraintValidator<ConsistencyValidation, String> { | |
@Autowired | |
private lateinit var lookUpRepository: LookUpRepository | |
@Autowired | |
private lateinit var eventBus: EventBus | |
lateinit var name: String | |
override fun initialize(constraintAnnotation: ConsistencyValidation) { | |
super.initialize(constraintAnnotation) | |
name = constraintAnnotation.name | |
} | |
override fun isValid(value: String, context: ConstraintValidatorContext?): Boolean { | |
val isExist = lookUpRepository.existsByMetaNameAndMetaValue( | |
metaName = name, | |
metaValue = value | |
).block()!! | |
if (!isExist) { | |
// publish event to the event handler not exist in db | |
eventBus.publish(GenericEventMessage( | |
ConsistencyValidationEvent( | |
key = ObjectId.get().toHexString(), | |
metaName = name, | |
metaValue = value | |
) | |
)) | |
} | |
return isExist | |
} | |
} | |
data class ConsistencyValidationEvent( | |
val key: String, | |
val metaName: String, | |
val metaValue: String | |
) { | |
fun toDomain() = LookUp( | |
key = key, | |
metaName = metaName, | |
metaValue = metaValue | |
) | |
} | |
// schema for the look up table | |
@Document | |
data class LookUp( | |
@Id | |
val key: String, | |
val metaName: String, | |
val metaValue: String | |
) | |
interface LookUpRepository: ReactiveCrudRepository<LookUp, String> { | |
fun existsByMetaName(metaName: String): Mono<Boolean> | |
fun existsByMetaValue(metaValue: String): Mono<Boolean> | |
fun existsByMetaNameAndMetaValue(metaName: String, metaValue: String): Mono<Boolean> | |
} | |
@Component | |
@ProcessingGroup("consistencyValidation") | |
class ConsistencyHandler(){ | |
@Autowired | |
private lateinit var repository: LookUpRepository | |
@EventHandler | |
fun on(event: ConsistencyValidationEvent){ | |
repository.save(event.toDomain()).block() | |
} | |
} | |
// would this work i'm not sure | |
data class RegisterAccountCommand( | |
val firstName: String, | |
val lastName: String, | |
// this will automatically create look up table for email | |
@ConsistencyValidation(name = "email") | |
val email: String | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment