I am trying to return a authentication token in response to a graphql query with username and password as arguments, but somehow graphql is always returning null
. I am able to print the token just before returning it.
var {
GraphQLObjectType,
GraphQLInt,
GraphQLList,
GraphQLString,
GraphQLSchema
} = require('graphql');
let MyUser = require('./modules/user/user');
const Query = new GraphQLObjectType({
name: 'Query',
description : 'UserQuery',
fields: function(){
return {
Token :{
type: GraphQLString,
description : "Authentication token",
args: {
user_name: { type: GraphQLString },
password: { type: GraphQLString },
},
resolve(root, args){
let user = new MyUser();
user.authenticateUser(args.user_name, args.password, function(result){
console.log("token :"+result);
return result;
})
}
}
}
}
});
const Schema = new GraphQLSchema({
query: Query
});
module.exports = Schema;
Query look like
query{
Token(user_name: "[email protected]"
password: "abc123")
}
Result
{
"data": {
"Token": null
}
}
what I am doing wrong here ?
The resolver must return the JSON value, or a promise that results in that value. In your example you're using a callback to fetch the actual REST query:
user.authenticateUser(args.user_name, args.password, function(result){
console.log("token :"+result);
return result;
});
This won't work since it doesn't immediately return a value. You can try something like this:
resolve(root, args){
let user = new MyUser();
return new Promise((resolve, reject) => {
user.authenticateUser(args.user_name, args.password, function(result){
console.log("token :"+result);
resolve(result);
});
})
}
I haven't ran this code to ensure it works, but this basic idea is to always return a value for your resolvers and callbacks, unfortunately, don't allow for this