Skip to content

Instantly share code, notes, and snippets.

@srmppn
Last active July 30, 2021 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srmppn/beb6b18e68a4084c7ac30342334a0993 to your computer and use it in GitHub Desktop.
Save srmppn/beb6b18e68a4084c7ac30342334a0993 to your computer and use it in GitHub Desktop.
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