0

I want to return data coming from db to the api. The data is being logged but not showing on the 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);

RESULT:

query
{
  getUsers {
    id
  }  
}

OUTPUT:

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field RootQuery.getUsers.",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "getUsers"
      ]
    }
  ],
  "data": null
}
3
  • what's the problem/question? Commented Feb 14, 2019 at 8:36
  • I wanted to return data coming from db to the api, the data is being logged but not showing on the graphql api. The api result I have pasted above. Commented Feb 14, 2019 at 8:39
  • Thanks for fixing the formatting! :) Commented Feb 14, 2019 at 10:38

3 Answers 3

1

This is your resolver:

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

A GraphQL resolver must return either a value or a Promise that will resolve to a value. However, here, you're not returning either. Keep in mind that callbacks are invoked asynchronously, so returning a value inside a callback does nothing (in most cases).

You really should use something like promise-mysql instead of mysql, but you can still wrap a callback with a Promise and return that Promise. Something like this should work:

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

2 Comments

can u also tell me code for the mutator, that how to add in this db. ?
That's a bit out of scope for this question. You'll need to make one query call to insert the new row, then fetch the inserted row using a second query call that selects the newly created row. I'm sure there's existing SO questions and tutorials on how to do that with the mysql driver; it's not really GraphQL-specific.
1
  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) ;
    });
  },

Your getUsers function doesn't return anything. I believe you're missing the return statement I've highlighted in the above comment.

Incidentally, it's best practices in GraphQL to ensure all the root fields (such as getUsers) are nullable, have a read of this article to find out why.

1 Comment

I have return result in the end.
1

delete (!) from field definition in schema

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
This worked for my case. ! in typescript is the Non-null assertion operator blog.logrocket.com/understanding-exclamation-mark-typescript. I am using schemaStitching to stitch two schemas together. My definition for the subSchema had ! after it. In the case where there is no data for the stitched schema, I got this error, because ! said my subSchema cannot be null. So removing ! meant it could be null. Thank you @idris-belarouci

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.