mysqlnode.jsparametersinquirer

Parametizing table name Node.js/mySQL?


So I have three mySQL database tables that I need to be able to add records to from inquirer. Rather than write three separate functions, I'd like to just have one efficient function that can do all three depending on the input.

The user is asked what they'd like to do, and the switch/case runs the first function with the set of inquirer questions they would need to answer

switch (response.toAdd) {
                case "New Employee":
                    return addACME(empQ);
                case "New Department":
                    return addACME(deptQ);
                case "New Role":
                    return addACME(roleQ);

The first function takes the necessary set of questions, has the user answer them, and then runs the second function with that

const addACME = (choice) => {
    return inquirer.prompt(choice)
        .then(response => {
            addToDB(response);
        });
}

But when I get to here is where I have problems. Obviously the tablename is employees not ?? so it will not work for depts/roles. I would need a way to track that as a variable and carry it through so that I could make the tablename also dynamic, but I'm not sure how I'd go about that?

const addToDB = acmeRecord => {
    connection.query("INSERT INTO employees SET ?", acmeRecord, (err, results) => {
        if (err) throw err;
        mainMenu();
    })
}

Solution

  • You can add the table name as a parameter to your function

    const addToDB = (tablename, record) => {
        connection.query(`INSERT INTO ${tablename} SET ?`, record, (err, results) => {
            if (err) throw err;
            mainMenu();
        })
    }
    

    and then call it like so

    switch (response.toAdd) {
                    case "New Employee":
                        return addACME("employees", empQ);
                    case "New Department":
                        return addACME("<department_table_name>", deptQ);
                    case "New Role":
                        return addACME("<role_table_name>", roleQ);