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)?
With validation logic inside the resolve
method, you have complete control over the generated user errors. Here is an example:
// data/mutations/createUser.js
import {
GraphQLObjectType as ObjectType,
GraphQLNonNull as NonNull,
GraphQLList as List,
GraphQLString as StringType
} from 'graphql';
import validator from 'validator';
import UserType from '../types/UserType';
export default {
type: new ObjectType({
name: 'CreateUserResult',
fields: {
user: { type: UserType },
errors: { type: new NonNull(new List(StringType)) }
}
}),
args: {
email: { type: new NonNull(StringType) },
password: { type: new NonNull(StringType) }
},
resolve(_, { email, password }) {
let user = null;
let errors = [];
if (validator.isNull(email)) {
errors.push(...['email', 'The email filed must not be empty.']);
} else if (!validator.isLength(email, { max: 100})) {
errors.push(...['email', 'The email must be at a max 100 characters long.']);
}
// etc.
return { user, errors };
}
};
See my blog post on this subject - Validation and User Errors in GraphQL Mutations
Alternatively, create type UserErrorType { key: String!, message: String! }
that can be used instead of plain strings when you compile the list of user errors to be returned to the caller.
mutation {
createUser(email: "[email protected]", password: "Passw0rd") {
user { id, email },
errors { key, message }
}
}
{
data: {
user: null,
errors: [
{ key: '', message: 'Failed to create a new user account.' },
{ key: 'email', message: 'User with this email already exists.' }
]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With