Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing MySQL Node.js models using node-mysql

I'm trying to find some good practices for writing MySQL models using node-mysql.

Here's what I have so far:

var client = app.settings.client; // Client is set in Express settings

var table = 'users';

var User = function() {

}

// Create the user with data from Facebook
User.prototype.createFromFacebook = function (name, first_name, last_name, email, location, gender, facebookId, facebookToken, callback) {
  client.query(
    'INSERT INTO ' + table +
    ' SET name = ?, first_name = ?, last_name = ?, email = ?, location = ?,' +
    ' gender = ?, facebook_id = ?, facebook_token = ?',
    [ name, first_name, last_name, email, location, gender, facebookId, facebookToken ],
    function selectCb(err, results, fields) {
      if(err) {
        callback(err);
      } else {
        callback(null, results);
      }
    }
  );
}

// Get user with just their email address
User.prototype.getByEmail = function (email, callback) {
  client.query(
    'SELECT * FROM ' + table +
    ' WHERE email = ?',
    [ email ],
    function selectCb(err, results, fields) {
      if(err) {
        callback(err);
      } else {
        callback(null, results);
      }
    }
  );
}
module.exports = User;

Any critiques or improvements on this would be awesome. Thanks!

like image 787
Josh Smith Avatar asked Dec 05 '11 17:12

Josh Smith


1 Answers

As a improvement, you can refactor your code

  1. Datasourceobject for db connection
const db = require(__dirname + '/myDatabaseInstance.js');

  1. Create UserSchema model user.js defines fields, data type, validation rules, etc.

user.schema.js

{
 "ID" : {
      "field" : "id",
       "type" : 'integer',
       "validation_rules" : "onlyInteger"     
  },
"name" : {
      "field" : "name",
      "type" : "string",
      "validation_rules": "usernameregex"   
 }
}

  1. Create Controller.js where you can have findAll, findById, create, update, delete, search API methods.
 class _controller {
        constructor(object, model_schema) {
            this._object = object;
            this._model_schema = model_schema;
        }
        setId(_id) {
            this.id = _id;
        }

        validateRules(validation_rules) {
            return new Promise((resolve, reject) => {
                let error = {};
                let validation = new Validator(this._object, validation_rules);
                if (validation.fails()) {
                    error.type = "validation";
                    error.errors = validation.errors.errors;
                    reject(error);
                } else {
                    resolve(true);
                }
            });
        };

        create() {
            return new Promise((resolve, reject) => {
                let response = {};
                let error = {};
                this.validation_rules= 
                UserSchema.getRules(this._model_schema).get_validation_rules;
                this
                    .validateRules(this.validation_rules )
                    .then(validation_result => {
                        db.insert(this.table, this._object)
                          .then(result => {
                                response.status = 201;
                                resolve(response);
                            });

                    })

            });
        }
})
  1. Create user.js which extends to common controller.js using user schema
 class user extends _controller {
        constructor(object) {
            super(object, "user_schema");
            this.object = object;
        }
  }

You can add new functionalities in user.js code.

like image 143
Prashant Biradar Avatar answered Oct 28 '22 13:10

Prashant Biradar