如何从MySQL查询返回json到GraphQL?

时间:2018-05-23 22:34:59

标签: javascript mysql json node.js graphql

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

编辑I:

如果我为JSON.parse更改了JSON.stringify,我在控制台中遇到了这个错误:

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

编辑II:

我在返回JSON.parse(解析)时修复了错误,但它没有工作:(我在GraphiQL中仍然遇到此错误:

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

我管理myPromise的代码现在就是这个......

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:

我们有这个字符串 {&#34;播放器&#34;:&#34; {\&#34; id \&#34;:11}&#34;} 使用JSON.stringify(解析)。我认为我必须只返回 {\&#34; id \&#34;:11} 。我怎样才能做到这一点?知道如何将json返回给GraphiQL吗?

编辑IV:

我修改了我的代码只返回带有return resolve(结果[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");
    });
};

2 个答案:

答案 0 :(得分:1)

问题应该是您在诺言得到解决之前就已经从解析器返回,因此您总是会得到null:

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

答案 1 :(得分:0)

您是否尝试过使用JSON.parse()而不是JSON.stringify?

您可能会在这里获得有关差异的更多信息: Difference between JSON.stringify and JSON.parse