如何从mysql查询返回json到graphql?

jhdbpxl9  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(401)

我是nodejs和qraphql的新手,我正在尝试对graphql进行一个简单的查询。在对mysql数据库进行查询之后,我的问题是我不知道如何将数据正确地发送到graphql以查看结果。
我得试着坚定决心,但没有用。我用json从mysql返回结果,结果不起作用。为什么在graphiql中看不到结果?我要怎么回心转意?
这是我进行查询并返回结果的函数:

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

编辑一:
如果我将json.stringify更改为json.parse,控制台中会出现以下错误:

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

编辑二:
我已经修复了返回json.parse(resolve)时的错误,但它不起作用:(我在graphiql中仍然得到这个错误:

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

我管理我的承诺的代码是。。。

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

编辑iii:
我们有一个带有json.stringify(resolve)的字符串{“player”:“{\”id\“:11}”。我想我只需要返回{“id\”:11}。我该怎么做?知道如何将json返回到graphiql吗?
编辑四:
我修改了我的代码,只返回带有返回解析(results[0].player)的json,但它不起作用!!!
这是我的实际代码:

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

b1zrtrql1#

你试过用json.parse()代替json.stringify吗?
您可以在这里获得更多关于差异的信息:json.stringify和json.parse之间的差异

6ovsh4lw

6ovsh4lw2#

问题应该是,在您的承诺得到解决之前,您已经从解析器返回,因此您总是得到空值:

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

您可以做的是,在您的解析器中,在您的承诺得到解决之前等待,如下所示:

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

相关问题