Home > Mobile >  GraphQL can't receive mysql data
GraphQL can't receive mysql data

Time:02-26

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.

CodePudding user response:

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
            }

CodePudding user response:

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(...))?)

  • Related