GraphQL resolver not waiting for db write

Viewed 349

Been trying to learn GraphQL and I have a graphql mutation that is successfully creating a user in a mysql db but the resolve fn isn't returning the id returned by the mysql query (accessed by result.insertId). However, if I log out the results, the logs have the correct values (I know I can clean this up a bit once this starts working). All the queries that fetch data work just fine. Anyone have any ideas? Thanks in advance.

resolve: async (parentValue, args) => {
    const res = await addUser(args)
    const id = await res.insertId
    console.log('Returning: ', id); // This logs out the correct id
    return await id  // In graphiql, the id returned is null and is returned WAY before the log above it.  Not sure why that write is so slow, but that's another issue
}

// addUser function defined in another file
module.exports = {
    addUser: (args) => {
        const {
          firstName,
          lastName,
          username,
          password,
          occupation,
          email
        } = args
        return db.query(`
        INSERT INTO users (firstName, lastName, userName, password, occupation, email)
    VALUES (?, ?, ?, ?, ?, ?)`,
      [
        firstName,
        lastName,
        username,
        password,
        occupation,
        email
      ])
  }
}

// Class to make wrap mysql with Promises (from https://codeburst.io/node-js-mysql-and-promises-4c3be599909b)

class Database {
  constructor(config) {
    this.connection = mysql.createConnection(config);
  }
  query(sql, args) {
    return new Promise((resolve, reject) => {
      this.connection.query(sql, args, (err, rows) => {
        if (err)
            return reject(err);
        resolve(rows);
      });
    });
  }
  close() {
    return new Promise((resolve, reject) => {
      this.connection.end(err => {
        if (err)
          return reject(err);
        resolve();
      });
    });
  }
}
module.exports = new Database(config);

** Update Instead of trying to return the id of the newly created field, I tried getting the id then fetching the newly created user and that works perfectly. So what am I doing wrong here? Why do I have to fetch the new user instead of just returning the id? I thought it might be because the type on the addUser mutation was set to UserType (that has fields id, firstName, lastName, etc), but I created a NewUserType that just has a field of id and that still didn't work. Would love to know what's going on here.

  resolve: async (parentValue, args) => {
    const res = await addUser(args)
    const id = await res.insertId
    return getUser(id)
  }
0 Answers
Related