问题描述:

I have a small ember application that gets data from mysql using node. Currently I use the following to fetch the customer data:

function handleGet(connection,req,res) {

var limit = ('undefined' === typeof req.params.limit) ? 200: req.params.limit;

connection.query('SELECT * FROM customer LIMIT ' + limit, function handleSql(err, rows) {

if (err){ logAndRespond(err,res); return; }

if (rows.length === 0){ res.send(204); return; }

res.send({customers : rows});

connection.release();

});

}

however I would not want to have a function for customers, another for users, etc.

How can I abstract this?

I could pass the table name to the function,no problem. The problem is that Ember expects the name of the table on the response. So I cannot change the line :

res.send({customers : rows});

to

res.send({tablename : rows});

since it sends literally the word 'tablename' rather than content of the variable, like this:

{"tablename":[{"id":1,"status":"n".....}]

Thanks!

网友答案:

Since the other answer already lectured you, here's the solution:

function handleGet(connection, req, res) {
    var limit = ('undefined' === typeof req.params.limit) ? 200: req.params.limit;
    var table = req.params.table || return logAndRespond(new Error("Missing table param", res));
    connection.query('SELECT * FROM ' + table + ' LIMIT ' + limit, function handleSql (err, rows) {
        if (err){ logAndRespond(err,res); return; }
        if (rows.length === 0){ res.send(204); return; }
        var result = {};
        result[table] = rows;
        res.send(result);
        connection.release();
    });
}
网友答案:

You have a typo that may be preventing it from sending the table name variable value. you have "tablemame" instead of "tablename".

Also, I would strongly suggest you remove actual SQL statements from any Javascript! A hacker could modify your code to run any SQL they wanted.

相关阅读:
Top