. Advertisement .
..3..
. Advertisement .
..4..
I don’t know what I’m doing wrong, but I’ve already lost a couple of days struggling with this. Here is my command line:
export default `
type User {
id: ID!
name: String!
email: String!
}
type Query {
allUsers: [User]
currentUser: User
}
type Mutation {
createAccount(name: String!, email: String!, password: String!): User
loginUser(email: String!, password: String!): User
updatePassword(email: String!, password: String!, newPassword: String!): User
deleteAccount(email: String!, password: String!): User
}
`
createAccount: async (
parent,
{ name, email, password },
{ User },
info
) => {
try {
// Check for invalid (undefined) credentials
if (!name || !email || !password) {
return 'Please provide valid credentials';
}
// Check if there is a user with the same email
const foundUser = await User.findOne({ email });
if (foundUser) {
return 'Email is already in use';
}
// If no user with email create a new user
const hashedPassword = await bcrypt.hash(password, 10);
await User.insert({ name, email, password: hashedPassword });
const savedUser = await User.findOne({ email });
return savedUser;
} catch (error) {
return error.message;
}
},
This returns:
Cannot return null for non-nullable field
I don’t have any experience with the “cannot return null for non-nullable field.” In this case, how should I change?
The cause:
The main issue with your resolver is that, in a variety of situations, it returns a string rather than a User object. According to your schema, createAccount can either return a User or null. Your resolver forces a returned string into an object because it was expecting one and then begins searching for User attributes on that object (such as email and name). As these are non-null properties on your User object, returning null or undefined for them causes an error because they don’t exist.
Solution:
Most likely, your resolver should just throw any errors that are required. They will then be included in the errors array that makes up your answer. For instance:
The response will look like the following if you receive a duplicate email:
Use the formatResponse configuration parameters or formatError for your middleware of Apollo server if you wish to change how errors are displayed to clients. Using custom errors, which let you add specific properties like code to more readily identify the problem type on the client side, is also a smart idea.
Finally, because your schema already has these inputs tagged as non-null, GraphQL will not need to check whether email, name or password are specified inside your resolver and will instead return an error if any of them are missing.