0

I have the code

private static Validation<ConstraintViolation, List<Person>> validatePersonDetail(
        List<PersonDetailRequest> personRequest) {
    
    for (PersonRequest request:personRequest) {
        
        if (isNull(request.getName())) {
            return invalid(new ConstraintViolation("name", "name cannot be empty"));
        }
        ..
        // more validations
        
        // build object
        Person.builder().name(request.getName()).build();
    }
    return valid([PERSON_LIST]);
}

I want to return Person List but not sure how to go with Vavr. I cannot use Validation combine as it contains nested validations for nested objects

raaeusagvc
  • 71
  • 6

2 Answers2

0

Suppose you just build Person when the list pass all validation, then map is what you need:

private static Validation<ConstraintViolation, List<Person>> validatePersonDetail(
        List<PersonRequest> personRequest) {

    for (PersonRequest request:personRequest) {

        if (isNull(request.getName())) {
            return invalid(new ConstraintViolation("name", "name cannot be empty"));
        }
        // more validations

    }
    return valid(personRequest.map(request->Person.builder().name(request.getName()).build()));
}
samabcde
  • 6,988
  • 2
  • 25
  • 41
-1

I would recommend something like this. return list of Error from validatePersonDetail and check if it is null or empty, if it is empty then go ahead with your execution ahead:

private void mainExecution() {
    Validation<ConstraintViolation> validationErrors = validatePersonDetail(personRequest);
    if(validatePersonDetail().isEmpty) {
        return valid([PERSON_LIST]);
    } else {
        throw new ValidationFailedException(validationErrors);
    }
}

private static Validation<ConstraintViolation> validatePersonDetail(
            List<PersonDetailRequest> personRequest) {
    Validation<ConstraintViolation> validations = new ArrayList<>();
    for (PersonRequest request:personRequest) {
        if (isNull(request.getName())) {
            return validations.add(new ConstraintViolation("name", "name cannot be empty"));
        }
        ..
        // more validations
    }
    return validations;
}
Antoine
  • 1,393
  • 4
  • 20
  • 26
  • I am using vavr. `Validation validations = new ArrayList<>();` can't use. Looking solutions using vavr's library only – raaeusagvc Nov 25 '21 at 07:49