Graphql,node.js和sql,对于不可为空的字段无法返回null

时间:2019-02-14 08:05:17

标签: sql node.js graphql

我想将来自db的数据返回给api。正在记录数据,但没有显示在graphql api上。

const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const { buildSchema } = require('graphql');
var mysql = require('mysql');

const app = express();  

//start mysql connection    
var connection = mysql.createConnection({    
  host     : 'localhost', //mysql database host name    
  user     : 'root', //mysql database user name    
  password : '', //mysql database password    
  database : 'test' //mysql database name    
});

connection.connect(function(err) {    
  if (err) throw err      
})    

//end mysql connection

app.use(bodyParser.json());    
app.use(    
  '/graphql',    
  graphqlHttp({
    schema: buildSchema(`
        type users {
          id: String!
          username: String!
          password: String!
          role: String!
          name: String!
          photo: String!
        }
        type RootQuery {
            getUsers: [users!]!
        }
        type RootMutation {
          createUsers(name: String): String
        }
        schema {
            query: RootQuery
            mutation: RootMutation
        }
    `),
    rootValue: {
      getUsers: () => {
        connection.query('select * from users', function (error, results, fields) {
          if (error) throw error;
          console.log(JSON.stringify(results))
          return JSON.stringify(results) ;
        });
      },
      createUsers: (args) => {
        const eventName = args.name;
        return eventName;
      }
    },
    graphiql: true
  })
);

app.listen(3000);

结果:

query
{
  getUsers {
    id
  }  
}

输出:

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field RootQuery.getUsers.",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "getUsers"
      ]
    }
  ],
  "data": null
}

2 个答案:

答案 0 :(得分:0)

  getUsers: () => {
    /*  return  */ connection.query('select * from users', function (error, results, fields) {
      if (error) throw error;

      //users = results;
      console.log(JSON.stringify(results));
      return JSON.stringify(results) ;
    });
  },

您的getUsers函数不返回任何内容。我相信您会丢失上面注释中突出显示的return语句。

顺便说一句,在GraphQL中,最好的做法是确保所有根字段(例如getUsers)都可以为空,请阅读this article来找出原因。

答案 1 :(得分:0)

这是您的解析器:

getUsers: () => {
  connection.query('select * from users', function (error, results, fields) {
    if (error) throw error;

    //users = results;
    console.log(JSON.stringify(results));
    return JSON.stringify(results) ;
  });
},

GraphQL解析器必须返回一个值或一个将解析为值的Promise。但是,这里您都不返回。请记住,回调是异步调用的,因此在大多数情况下,在回调内返回值都不会执行任何操作。

您确实应该使用promise-mysql之类的东西代替mysql,但是您仍然可以使用Promise包装回调并返回该Promise。这样的事情应该起作用:

getUsers: () => {
  // Note, we have to return the Promise here
  return new Promise((resolve, reject) => {
    connection.query('select * from users', (error, results, fields) => {
      if (error) {
        reject(error)
      } else {
        // Don't stringify
        resolve(results)
      }
    })
  })
},