Recently, I have been experimenting with typegraphql alongside apollo-server, typeorm, and bcrypt in typescript. I encountered a peculiar issue when running the mutation query using the resolver below. The error 'Cannot return null for non-nullable field Mutation.create' keeps popping up, even though the data is successfully saved to the database with a hashed password (confirmed via console.log). Strangely, the error only occurs when executing the mutation query in the browser.
Here is the mutation resolver snippet:
@Mutation(returns => Users)
create(@Arg("newuser") newuser: UserInput): Promise<Users> | any {
bcrypt.hash(newuser.loginpassword, 12)
.then( hash => {
const new_user = this.usersRepository.create(newuser);
new_user.loginpassword = hash;
return this.usersRepository.save(new_user);
});
}
Interestingly, when the lines related to bcrypt are commented out as shown below, no errors are thrown (although the password remains unhashed):
@Mutation(returns => Users)
create(@Arg("newuser") newuser: UserInput): Promise<Users> | any {
// bcrypt.hash(newuser.loginpassword, 12)
// .then( hash => {
const new_user = this.usersRepository.create(newuser);
//new_user.loginpassword = hash;
return this.usersRepository.save(new_user);
//});
}
In both scenarios, the mutation successfully creates and saves the record, and hashing with bcrypt works fine too.
I've been struggling with this issue for the past couple of weeks, scouring through similar threads such as this one (Graphql, node.js and sql,Cannot return null for non-nullable field).
In the initial version (with bcrypt code), what could be causing the error? I've experimented with changing the return type to Users | any from Promise | any, and introducing another .then statement to return the Users object instead of a promise object?
In Graphql, node.js and sql,Cannot return null for non-nullable field, Mr. Benjie suggests looking into . However, I'm uncertain about how to implement a nullable Mutation.create. Can anyone offer guidance or provide an example?
If I define the return declaration of create as 'Promise<Users>' instead of 'Promise<Users> | any', typescript complains and expects a return statement. But adding a return statement at the end causes create to exit prematurely. Is declaring the return type as 'Promise<Users> | any' the correct approach?
Appreciate all the help and insights.