Nicolas Demoisson Nicolas Demoisson - 6 months ago 15
SQL Question

Node.js - MySQL API, multi GET functions

I'm new in making API. I use Node.js and MySQL.
The fact is I have two GET function to get all users and one to get user by ID.
Both function are working when they are alone implemented. If both of them are implemented the function to get all user try to enter in the function to get user by ID so the API crash.
So here is my model users.js

var connection = require("../connection");

function Users()
{
//GET ALL USERS
this.get = function(res)
{
console.log('Request without id');
connection.acquire(function(err, con)
{
con.query('SELECT * FROM users', function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to get users'})
else
res.send(result);
});
});
}

//GET USER BY ID
this.get = function(id, res)
{
console.log('Request with ID');
connection.acquire(function(err, con)
{
if (id != null)
{
con.query('SELECT * FROM users WHERE id = ?', id, function(err, result)
{
con.release();
if (err)
res.send({status: 1, message: 'Failed to find user: ' + id});
else if (result == "")
res.send({status: 1, message: 'Failed to find user: ' + id});
else
res.send(result);
});
}
});
}


And here is the routes.js

var users = require('./models/users');

module.exports = {
configure: function(app) {
app.get('/users/', function(req, res) {
users.get(res);
});

app.get('/users/:id/', function(req, res) {
users.get(req.params.id, res);
});


Do you have any idea why ?
Thanks for help :)

Answer

You can't have two functions with the same name in the same scope.

You have to rename your functions

/**
* Get all users
*/
this.get = function(res) {...}

/**
* Get user by id
*/
this.getById = function(id, res) {...}

Or you can have one function and check if an id is provided

this.get = function(id, res) {
  if ( Number.isInteger(id) ) {
    // return the user
  } else {
    res = id;
    // return all users
  }
}