Gordon Clark
Gordon Clark

Reputation: 11

GraphQL + Sequelize resolver giving null data

Technologies in use:

I am trying to get graphQL working on my node server. Where I am specifically having issues is with the graphql resolver.

I have the following code, which works fine.

let User = require('./server/models').User;
let data = User.find({where: {email: "[email protected]"}})
    .then(function (foundUser) {
            console.log(foundUser.dataValues);
            return foundUser.dataValues;
    });

const resolvers = {
    Query: {
        user(root, args){
            return data;
        }
    }
};

When the client queries the graphql endpoint:

query Query{
  user(email:"[email protected]") {
    email
  }
}

They always get:

{
  "data": {
    "user": {
      "email": "[email protected]"
    }
  }
}

Which is fine! That is the expected behavior. As is, any parameter can get passed into the query with user(email:"[email protected]") and the results will be the same. Again, that's expected.

When I move the code however, so that the request for data from the database is IN the resolver like so:

const resolvers = {
    Query: {
        user(root, args){
            User.find({where: {email: "[email protected]"}})
                .then(function (foundUser) {
                    console.log(foundUser.dataValues);
                    return foundUser.dataValues;
                });
        }
    }
};

the client will always get this as a response from the graphql endpoint using the same query as before (the console.log outputs the appropriate information however):

{
  "data": {
    "user": null
  }
}

I suspect I'm failing to understand how apollo-server-express / graphql-tools handles the promise, but I'm not really sure how to move forward from this point. Any help is much appreciated.

Upvotes: 1

Views: 1477

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

You just need to add a return before User to ensure your Promises are correctly chained.

const resolvers = {
  Query: {
    user(root, args){
      User.find({where: {email: "[email protected]"}})
        .then(function (foundUser) {
          return foundUser.dataValues;
        });
    }
  }
};

In your earlier code (when the call to your model resided outside of the resolver), you were returning data inside of the resolver. In this case, data was not actually your database query result but a Promise that would resolve to that query result. In your updated code, you still have a Promise, but you don't return it inside your resolver function. GraphQL will take the return value and await it if it's a Promise, or otherwise use the value as is -- since you effectively return undefined, that's what the resolver uses for the value of user.

Upvotes: 1

Related Questions