0

I am trying to use GraphQL with mysql in a node js express server.

but I am getting this error everytime I run my query

here is the error:

{
  "errors": [
    {
      "message": "Expected Iterable, but did not find one for field \"RootQueryType.getAllGoals\".",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "getAllGoals"
      ]
    }
  ],
  "data": {
    "getAllGoals": null
  }
}

here is my Graphql Query:

query {
  getAllGoals {
    title
    progress
    goal
  }
}

I get the result expected from "SELECT * FROM (my table)", but it gives me an error when I try to return it for GraphQL from the resolver as shown in the code below:

const RootQuery = new GraphQLObjectType({
    name: "RootQueryType",
    fields: {
        getAllGoals: {
            type: new GraphQLList(GoalType),
            resolve(parent, args) {
                return db.query("SELECT * FROM myTable", (err, result) => {
                    if (err) throw err

                    console.log(JSON.parse(JSON.stringify(result)))
                    return JSON.parse(JSON.stringify(result))
                })
            }
        }
    }
})

I have checked to see if I have any conflicts in my GraphQLObjectType GoalType, but I had none.

2 Answers 2

2

I have fixed it, I just needed to make a promise that included the query (as shown below):

async resolve(parent, args) {
                var p = new Promise((resolve, reject) => {
                    db.query("SELECT * FROM myTable", (err, result) => {
                        console.log(JSON.parse(JSON.stringify(result)))
                        resolve(JSON.parse(JSON.stringify(result)))
                    })
                })
                return p
            }
Sign up to request clarification or add additional context in comments.

1 Comment

util.promisify(db.query) should have the same effect: It wraps the db.query in a promise that resolves to the result (or rejects with the err). Strange it didn't work for you.
0

Your resolve method returns whatever db.query returns, but this is not what GraphQL expects: It expects the result of the query, or a promise that resolves to this result. You can use util.promisify to obtain such a promise.

If you also want to log the result, use a .then method as shown here:

resolve(parent, args) {
  return util.promisify(db.query)("SELECT * FROM myTable")
  .then(result => {
    console.log(result);
    return result;
  });
}

(What's the purpose of JSON.parse(JSON.stringify(...))?)

1 Comment

It didn't work it still gives me the same error message in GraphiQL. But it has logged me the values I expect in the console

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.