Search code examples
javascriptnode.jsexpressnode-sqlite3

Many specific object properties to array


I use sqlite3 in my express app, and when user add new account to my system I use this code to add info to database:

db.run(`INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
    [this.uuid, this.email, this.pass, this.device, this.user, this.pet, this.gold, this.is_active],
    function (err) {
        if (err) {
            return console.log(err.message);
        }
    });

db - is my sqlite3 instance

I am sure there is should be a way to code it better (maybe something with spread? ). But I don't understand how to get only specific properties from 'this' (it contains other properties, that i don't need in my database)


Solution

  • You could create an array of the properties to extract from this, then .map it:

    const props = 'uuid email pass device user pet gold is_active'.split(' ');
    db.run(
      `INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
      props.map(prop => this[prop]),
      function(err) {
        if (err) {
          return console.log(err.message);
        }
      }
    );
    

    Could be even less repetitive (and less error-prone) by saving the string of properties so you can both split on it and pass to the first argument of .run:

    const propsStr = 'uuid, email, pass, device, user, pet, gold, is_active';
    const props = propsStr.split(', ');
    db.run(
      `INSERT INTO accounts(${propsStr}) VALUES(${propsStr.replace(/\w+/g, '?')})`,
      props.map(prop => this[prop]),
      function(err) {
        if (err) {
          return console.log(err.message);
        }
      }
    );