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");
    });
};

2 Answers 2

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);
};
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Yes with JSON.parse I've got an error in the server :(
Thanks @Denis Kovzelyuk but If I try to return JSON.parse(resolve) I've got an error. I have edited my original post with the error. What happend?

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.