首页 > 代码库 > node crypto--sh1-md5

node crypto--sh1-md5

//tool.js  文件
var crypto=require(‘crypto‘);function sha1(str){ return crypto.createHash(‘sha1‘).update(str).digest(‘hex‘); }function md5(str){ return crypto.createHash(‘md5‘).update(str).digest(‘hex‘);}var _extends=function(obj1,obj2){ console.log(‘_extends‘) //继承 for(var k in obj1){ obj2[k]=obj1[k] }}module.exports={ sha1:sha1, md5:md5, _extends:_extends}
//model.js文件

var util=require(‘util‘);
const PREFIX=‘blog_‘;
var db=require(__dirname+‘/../config/db.js‘);
//console.log(db);
function model(){
this.prefix=PREFIX;
this.db=db;
}

model.prototype.insert=function(obj,callback){
//insert into table() values()
//{username:‘guojikai‘,age:‘55‘,sex:‘1‘}
var table=this.table;
var fields=‘‘;
var values=‘‘;
for( var k in obj){
fields+=k+‘,‘;
values=values+"‘"+obj[k]+"‘,"
}
fields=fields.slice(0,-1);
values=values.slice(0,-1);
var sql="INSERT INTO "+this.prefix+table+‘(‘+fields+‘) VALUES(‘+values+‘)‘;
// console.log(sql+‘--------------‘);
this.db.query(sql,callback);
}
model.prototype.findOne=function (where,callback){ //查找一条;
// whre is arr; [{id:1},{username:admin}];
var table=this.table;
var _WHERE=‘‘;
if(util.isObject(where)){
_WHERE+=‘WHERE ‘;
for(var k in where){
_WHERE+=k+"=‘"+where[k]+"‘ AND ";
}

_WHERE=_WHERE.slice(0,-4);
}else if(typeof where ==‘string‘){
_WHERE=‘WHERE ‘+where;
}
var sql="SELECT * FROM "+this.prefix+table+‘ ‘+_WHERE+‘ LIMIT 1‘;
console.log(sql);
this.db.query(sql,function(err,data){
if(err){
callback(err,0);
}else{
callback(err,data[0]);
}
});
}
model.prototype.select=function(fields,callback){ //查找所有;
var _FIELDS=‘‘;
for(var i=0;i<fields.length;i++){
_FIELDS+=fields[i]+‘,‘;
}
_FIELDS=_FIELDS.slice(0,-1);
var sql="SELECT "+_FIELDS+" FROM "+this.prefix+table;
console.log(sql);
this.db.query(sql,callback);
}

model.prototype.update=function(sets,where,callback){
var _SETS=‘‘;
var _WHERE=‘‘;
var table=this.table;
for(var k in sets){
_SETS+=k+"=‘"+sets[k]+"‘,";
}
_SETS=_SETS.slice(0,-1);
for(var k2 in where){
_WHERE+=k+"=‘"+where[k2]+"‘ AND ";
}
//update table set username=‘admin2‘,age=‘55‘ where id="5";
var sql="UPDATE "+this.prefix+table+‘ SET ‘+_SETS+‘ ‘+_WHERE;
this.db.query(sql,callback);
}
model.prototype.del=function(where,callback){
var table=this.table;
var _WHERE=‘‘;
for(var k2 in where){
_WHERE+=k+"=‘"+where[k2]+"‘ AND ";
}
var sql="DELETE FROM "+this.prefix+table+‘ ‘+_WHERE;
this.db.query(sql,callback);
}

module.exports=new model();

// users.js 文件;

var model=require(‘./model.js‘);
var tool=require(‘../tool.js‘);
function User(){
this.table="users";
this.name="user";
}
var user=new User();
tool._extends(model,user);

module.exports=user

实现模块化 



  

node crypto--sh1-md5