W
W
Wasya UK2018-06-13 15:41:51
MySQL
Wasya UK, 2018-06-13 15:41:51

How to do proper insert in mysql + node.js?

I'm trying to make a competent creation of a table if if it does not exist when the data is first written to it, but the code turned out not very beautiful, can I write better?

insert(tableName, values) {
    return new Promise((resolve, reject) => {
      this.pool.query(`INSERT INTO ${tableName}(username, password, image) VALUES('${values.join("', '")}')`)
        .then(resolve)
        .catch(err => {
          // if TABLE doesn't exists
          if (err.errno == 1146) {
            this.createTable(tableName)
              .then(newTable => {
                console.log("New table created!\n", newTable);
                this.insert(tableName, values)
                  .then(resolve)
                  .catch(reject);
              })
              .catch(reject);
          }
        });
    });
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2018-06-13
@RidgeA

I would try something like this:

function insert(tableName, values) {
  return this.pool.query(`INSERT INTO ${tableName}(username, password, image) VALUES('${values.join("', '")}')`)
    .catch(err => {
      // if TABLE doesn't exists
      if (err.errno == 1146) {
        return this.createTable(tableName)
          .then(newTable => {
            console.log('New table created!\n', newTable);
            return this.insert(tableName, values);
          })
      } else {
        throw err;
      }
    });
}

1. if "this.pool.query" returns a promise, then there is no point in creating a new one.
2. If you return prompt from then or catch, then you can continue the chain
3. In this SQL Injection code - depending on the package used, you need to look at how to correctly pass parameters to the request in order to avoid this vulnerability

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question