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?