Skip to content

Instantly share code, notes, and snippets.

@srmppn
Last active Jul 30, 2021
Embed
What would you like to do?
Set-based consistency validation.
@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