How to raise multiple validation errors in graphql-spring-boot when using resolvers?
Asked Answered
P

1

7

I am using the graphql-spring-boot library, and using the resolver objects to resolve the value of the input query.

Here's an example:

@Component
public class BookResolver implements GraphQLQueryResolver {

    @Autowired
    private BookImpl bookImpl;

    @Autowired
    private GraphqlValidator validator;

    public GetBookOutput getBooks(GetBookQuery getBookQuery) {  

        validator.validateBookInputQuery(getBookQuery);

        GetBookOutput output = bookImpl.getBook(getBookQuery)

        return output;
    }
}

In the above code, I want to validate the getBookQuery, and raise custom errors in the response sent to the client. The input getBookQuery type contains a string of numbers.

Here's how I implemented the GraphqlValidator class:

@Component
public class GraphqlValidator {

    private static final String BOOK_NUMBER_REGEX = " *[0-9]+( *, *[0-9]+)* *";

    public void validateBookInputQuery(GetBookInputQuery getBookInputQuery) {
        String bookNumber = getBookInputQuery.getBookNumber();

        if (!isValidValueForRefVal(bookNumber, BOOK_NUMBER_REGEX)) {
            throw new GraphqlInvalidFieldException("Input type getBookInputQuery Invalid", "bookNumber", bookNumber);
        }
    }
}

Inside the validateBookInputQuery function I throw an exception, which is implemented from GraphQLError:

@SuppressWarnings("serial")
public class GraphqlInvalidFieldException extends RuntimeException implements GraphQLError{

    private Map<String, Object> extensions = new HashMap<>();
    String message;

    public GraphqlInvalidFieldException(String message, String fieldname, String arg) {
        //super(message);
        this.message = message;
        extensions.put(fieldname, arg);
    }

    @Override
    public List<SourceLocation> getLocations() {
        return null;
    }

    @Override
    public Map<String, Object> getExtensions() {
        return extensions;
    }

    @Override
    public ErrorType getErrorType() {
        return null;
    }

    @Override 
    public String getMessage() {
        return message;
    }

}

By doing so I was able to validate a single field and send the custom error message to the client. However, in a more complex scenario, the input type GetBookQuery will contain not only the bookNumber, but also the bookName and Author. In other words, the input field will contain multiple fields that need to be validated. I want to be able to validate all the fields and group all errors together and send them to the client at once. Does anyone please help me with that?

Pren answered 16/7, 2018 at 18:3 Comment(0)
H
-1

Your validator could add errors (field and description) to a list as you run through validation, then pass that into the exception at the end to be thrown if the list isn't empty.

Harrovian answered 28/1, 2019 at 23:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.