2

I have an input object as

class Person {

    private String name;
    private String email;
    private String phone;
    private Address address;

    public static class Address {

        private String city;
        private String pincode;
        private String street;
        private AddrDetails details;

        public static class AddrDetails  {

            private String state;
            private String country;

        }
    }
}

I am using vavr Validations to validate the input

public static Validation<Seq<ConstraintViolation>, PersonDetailsModel> validatePerson(PersonDetailsRequest request) {
    Validation
        .combine(
            validateName("name", request.getName()),
            validateEmail("email", request.getEmail()),
            validatePhone("phone", request.getPhone()),
            validateAddress(request.getAddress())
        ).ap((name, email, phone, address) -> new PersonDetailsModel(name, email, phone, address);
}

public static Validation<Seq<ConstraintViolation>, Person.Address> validateAddress(
  Person.Address request) {

     return Validation
        .combine(..
        ).ap((..) -> new Person.Address(..);

}

In the second function, it returns Seq of ConstraintViolation while validatePerson expects only ConstraintViolation which is why it is failing although I have to add one more level of nesting of validations for AddrDetails. How to handle nested objects validations with this approach.

I am not sure about how shall I go ahead?

raaeusagvc
  • 71
  • 6

1 Answers1

0

In our project we call .mapError(Util::flattenErrors) after .ap. I have the feeling that there is a better way, but this at least solves the nesting.

The method in the Util class looks like this :

public static Seq<ConstraintViolation> flattenErrors(final Seq<Seq<ConstraintViolation>> nested) {
    return nested
            .flatMap(Function.identity())
            .distinct(); // duplicate removal
}
jvwilge
  • 2,474
  • 2
  • 16
  • 21