I would like to validate input provided by user during mutation and then provide errors if there are some invalid fields provided.
There is a question which answers the question for GraphQL-JS here
I want to ask this question about implementation using GraphQL-Java.
Let's say you have a form which posts data to API server. The API server validates the input and returns JSON object. If the input is invalid an error objects like the one below is returned.
{errors: {field1: "is required"}}
How do we handle and serve these kind of errors when using GraphQL? How and where should data validation be implemented (should that be part of GraphQL or should it be inside each resolve function)?
The graphql-java implementation has a class for checking if the query is not valid (i.e. graphql.validation.Validatior
). That way you can validate your query string before executing them.
If the query is invalid you can create a method that takes List<ValidationError>
as a parameter that generate the error response.
Example:
List<ValidationError> errors = validator.validateDocument(graphQLSchema, requestString);
if (!errors.isEmpty()) { return executeError(errors); }