spring-data-couchbase icon indicating copy to clipboard operation
spring-data-couchbase copied to clipboard

Support JSR303 Validation in ReactiveCouchbaseRepository [DATACOUCH-496]

Open spring-projects-issues opened this issue 5 years ago • 0 comments

Leonardo Duarte opened DATACOUCH-496 and commented

It would be nice to have JSR303 Validation support in ReactiveCouchbaseRepository:

 

Hello, I'm using spring-data-couchbase's ReactiveCouchbaseRepository and it seems there isn't support for using JSR303 validation (though there is in the non-reactive counterpart via event listener). I was wondering if there is a reason why it isn't supported, curious if maybe it hasn't been implemented cause it doesn't make sense maybe? I played around with a naive implementation of it by modifying RxJavaCouchbaseTemplate and was wondering if it would be possible to get feedback on it.

https://github.com/spring-projects/spring-data-couchbase/compare/master...l30thelion:master

 

Excerpt in RxJavaCouchbaseTemplate:

private <T> Observable<T> doPersist(T objectToPersist, PersistType persistType, PersistTo persistTo, ReplicateTo replicateTo) {
        validateBeforePersist(objectToPersist);  // add validation here??
        // If version is not set - assumption that document is new, otherwise updating
        Long version = getVersion(objectToPersist);
        Func3<RawJsonDocument, PersistTo, ReplicateTo, Observable<RawJsonDocument>> persistFunction;

 

Add in RxJavaCouchbaseTemplate:

    public void setValidator(final Validator validator) {
        this.validator = validator;
    }

    private <T> void validateBeforePersist(T objectToPersist) {
        if (validator != null) {
            Set violations = validator.validate(objectToPersist);
            if (!violations.isEmpty()) {
                throw new ConstraintViolationException(violations);
            }
        }
    }

 

Usage in my project opting-in by adding a validator from the context:

@Configuration(proxyBeanMethods = false)
class CouchbaseConfiguration {

    @Bean(name = [BeanNames.RXJAVA1_COUCHBASE_TEMPLATE])
    fun reactiveCouchbaseTemplate(
            @Qualifier("springBootCouchbaseConfigurer") couchbaseConfigurer: CouchbaseConfigurer,
            mappingCouchbaseConverter: MappingCouchbaseConverter,
            translationService: TranslationService,
            validator: Validator? // javax.validation.Validator
    ): RxJavaCouchbaseTemplate? {
        val template = RxJavaCouchbaseTemplate(
                couchbaseConfigurer.couchbaseClusterInfo(),
                couchbaseConfigurer.couchbaseClient(),
                mappingCouchbaseConverter,
                translationService)
        // opt-in to use validation
        template.setValidator(validator)
        return template
    }

}

Affects: 3.2.3 (Moore SR3)

spring-projects-issues avatar Dec 26 '19 00:12 spring-projects-issues