2

I'm newbie with nodejs and qraphql and I'm trying to make a simple query to graphql. After making the query to a MySQL database my problem is that I don't know how to send the data correctly to graphql to see the result.

I have to try to stringfy the resolve but it doesn't work. I return the result from mySQL with an json and it doesn't work. Why I can't see the result in Graphiql? How I have to return the resolve?

This is the function where I make the query and return the result:

let getPlayer = (args) => {
    let id = args.id;
    console.log("id: " + id);
    let myPromise = new Promise((resolve, reject) => {
        const connection = mysql.createConnection(config.ddbb_connection);
        connection.connect();
        connection.query("select json_object('id', id) as player from tbl003_player where id = " + id, 
                        function (error, results, fields) {
            if (!error){
                if (results.length > 0){
                    resolve(results[0]);
                    console.log("resultado: " + results[0]);
                }else{
                    reject(new Error("No se ha encontrado ninguna jugadora con el ID: " + id));
                }
            }else{
                reject(new Error("Se ha producido un error de acceso a BBDD"));
            }             
          });
        connection.end();        
    });
    console.log("Salgo de la consulta");
    myPromise.then((resolve) => {
        console.log("resolve: " + JSON.stringify(resolve));
        return resolve;
    },(error) => {
        console.log(error);
        return error;
    });
};

Edit I:

If I change JSON.stringify for JSON.parse I've got this error in the console:

(node:31898) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at myPromise.then (/home/josecarlos/Workspace/graph-ql/primer-server-express/routes-api.js:68:21)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:31898) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing insideof an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:31898) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Edit II:

I have fixed the error when I return JSON.parse(resolve) but it doesn't work :( I'm still getting this error in GraphiQL:

{
  "data": {
    "player": null
  }
}

The code where I manage myPromise is now this ...

myPromise.then((resolve) => {
    console.log("resolve: " + JSON.stringify(resolve));
    data = JSON.parse(resolve);
    return data;
},(error) => {
    console.log(error);
    return error;
}).catch(() => {
    console.log("Entro dentro del catch");
});

Edit III:

We've got this string {"player":"{\"id\": 11}"} with JSON.stringify(resolve). I think that I have to return just only {\"id\":11}. How can I do that? Any idea how to return a json to GraphiQL?

Edit IV:

I have modified my code to return just only the json with return resolve(results[0].player) and it doesn't work!!!

This is my actual code:

let getPlayer = (args) => {
    let id = args.id;
    console.log("id: " + id);
    let myPromise = new Promise((resolve, reject) => {
        const connection = mysql.createConnection(config.ddbb_connection);
        connection.connect();
        connection.query("select json_object('id', id) as player from tbl003_player where id = " + id, 
                        function (error, results, fields) {
            if (!error){
                if (results.length > 0){
                    resolve(results[0].player);
                    console.log("resultado: " + results[0].player);
                }else{
                    reject(new Error("No se ha encontrado ninguna jugadora con el ID: " + id));
                }
            }else{
                reject(new Error("Se ha producido un error de acceso a BBDD"));
            }             
          });
        connection.end();        
    });
    console.log("Salgo de la consulta");
    myPromise.then((resolve) => {
        console.log("resolve: " + JSON.stringify(resolve));
        return JSON.parse(resolve);
    },(error) => {
        console.log(error);
        return error;
    }).catch(() => {
        console.log("Entro dentro del catch");
    });
};
José Carlos
  • 2,850
  • 12
  • 59
  • 95

2 Answers2

2

The issue should be that you've returned from your resolver before your promise gets resolved, thus you always get null:

{
  "data": {
    "player": null
  }
}

What you can do is, in your resolver wait before return util your promise has been resolved, something like this:

async getPlayer(obj, args, context) => {
    ...
    let myPromise = new Promise((resolve, reject) => {
        ...
    });
    console.log("Salgo de la consulta");
    let result;
    try {
      result = await myPromise;
    } catch(error) {
      return error;
    }
    return JSON.stringify(result);
};
Yuci
  • 27,235
  • 10
  • 114
  • 113
0

Have you tried to use JSON.parse() instead of JSON.stringify?

You might get more info about the difference here: Difference between JSON.stringify and JSON.parse