Search code examples
node.jsnode-mysql

Is it possible to make unified insert function


So I have this piece of code, but I can't know how many arguments the function will take before I actually use it

function insert(...args) {
    return new Promise((resolve, reject) => {
        //                               ↓↓↓ - here is the problem
        db.query('INSERT INTO `?` VALUES(?,?,?,?,?,?);', args, (err, rows) => {
            return err ? reject(err) : resolve(rows);
        });
    });
}

Is it possible to modify this function so it will allow me to insert as many arguments as I need?


Solution

  • The simplest solution would probably be, using args.length to generate the appropriate number of ?

    function insert(...args) {
        return new Promise((resolve, reject) => {
            let qm = Array(args.length-1).fill('?', 0).join(',');
            let query = `INSERT INTO \`?\` VALUES(${qm});`
            db.query(query, args, (err, rows) => {
                return err ? reject(err) : resolve(rows);
            });
        });
    }
    

    But you should probably stick to Wiktor Zychla's suggestion, and don't try to write your own query generator. Especially -- no offense -- if you need to ask questions on that level ...