orm-mysql
v0.1.7
Published
Tiny ORM with Mysql
Downloads
9
Readme
Tiny ORM with Mysql to tiny project.
Installation
$ npm install orm-mysql
Usage
file : User.js
var Model = require('orm-mysql')( require('./config-sql.js'));
class User extends Model{
/**
* [constructor description]
* @return {[type]} [description]
*/
constructor(){
super();
this._table = 'User';
this._referer = 'id';
}
/**
* [_treatBeforeInsert description]
* @param {[type]} oData [description]
* @return {[type]} [description]
*/
_treatBeforeInsert( oData){
oData.nom = oData.nom.toLowerCase();
oData.prenom = oData.prenom.toLowerCase();
}
/**
* [completeName description]
* @return {[type]} [description]
*/
get completeName(){
return `${this.nom} ${this.prenom}`;
}
}
module.exports = new User();
Quick start
var User = require('./user.js');
var oPromise = User.one("`id` = '2'");
var oPromises = User.all();
//ONE USER
oPromise.then(( oUser)=>{
// read
console.log( oUser.nom, oUser.prenom, oUser.completeName);
// update
oUser.nom = 'lorem';
oUser.save().then(()=>{ console.log('saved OK ')});
}).catch((e)=>{
console.log(e);
});
// ALL USERS
oPromises.then( ( aUser)=>{
aUser.map( (oUser)=>{
console.log( oUser.nom, oUser.prenom, oUser.completeName);
})
})
Overview
Create
var User = require('./user.js');
var oPromise = User.create({
prenom : "john",
nom : "dupond"
}).then( ( oUser)=>{
console.log( `${oUser.completeName} created`);
});
Read
To read One element
var User = require('./user.js');
User.one(" `prenom` = 'john' ").then( ( oUser)=>{
console.log( `Hi ! ${oUser.completeName}`);
});
To read Multi element
var User = require('./user.js');
User.all().then( ( aUsers)=>{
aUsers.map((oUser)=>{
console.log( `Hi ! ${oUser.completeName}`);
})
});
Update
var User = require('./user.js');
User.one(" `prenom` = 'john' ")
.then( ( oUser)=>{
oUser.nom = "Doe";
oUser.save().then((oUser)=>{
console.log( `${oUser.completeName} updated`);
});
});
DELETE
var User = require('./user.js');
var oPromiseDel = User.create({
prenom : "alphonse",
nom : "dupond"
})
.then(( oUser)=>{
return oUser.destroy();
});
oPromiseDel.then(()=>{
console.log('sup');
});
CUSTOM
var User = require('./user.js');
User.customFind('SELECT * FROM user WHERE prenom = ?', 'john')
.then(( aUsers)=>{
aUsers.map((oUser)=>{
console.log( `custom -> Hi ! ${oUser.completeName}`);
})
});