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!
As a improvement, you can refactor your code
const db = require(__dirname + '/myDatabaseInstance.js');
user.schema.js
{
"ID" : {
"field" : "id",
"type" : 'integer',
"validation_rules" : "onlyInteger"
},
"name" : {
"field" : "name",
"type" : "string",
"validation_rules": "usernameregex"
}
}
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);
});
})
});
}
})
class user extends _controller {
constructor(object) {
super(object, "user_schema");
this.object = object;
}
}
You can add new functionalities in user.js code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With