user9227001
user9227001

Reputation:

How to return results of a query? Mysql nodejs

I am using mysql package from https://www.npmjs.com/package/mysql

So basically I have this function in a file:

module.exports.listGames = (id) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }

  connection.query(query, function(err, results) {
    if (err) {
      throw err;
    }
    console.log(results);
  });
}

and I want to return those results in the json format

so I can call it in another file which is this function:

function sendGames(req, res) {
    const games = db.listGames(req.query.game);
    res.json(games);
}

so my question is, How can I return the results from that query?

Upvotes: 1

Views: 7900

Answers (2)

Riajul Islam
Riajul Islam

Reputation: 1483

module.exports.listGames = (id) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }

  connection.query(query, function(err, results) {
    if (err) {
      throw err;
    }
    return (results);
  });
}

Declare javascript async function and call the method from here.

async function  sendGames (req, res) {
    var games = await db.listGames(req.query.game);
    res.json(games);
}

Upvotes: 0

Daniel Jee
Daniel Jee

Reputation: 664

You can either

  1. Use callback
module.exports.listGames = (id, cb) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }

  connection.query(query, function(err, results) {
    if (err) {
      throw err;
    }
    cb(results);
  });
}

module.exports.listGames(12, (results) => {
console.log(results);
})
  1. Use promise
module.exports.listGames = (id) => {
  let query = 'SELECT * FROM test';
  if (id) {
    query += 'WHERE userid = ' + connection.escape(id);
  }
  return new Promise((resolve, reject) => {
    connection.query(query, function(err, results) {
      if (err) {
        throw err;
      }
      resolve(results);
    });
  })

}

module.exports.listGames(12).then(results => console.log(results)

You can encode the response from mysql query to JSON using JSON.stringify.

Upvotes: 2

Related Questions