const redis = require('redis');
const bcrypt = require('bcrypt');
const db = redis.createClient();
function User(obj) {
for (let key in obj) {
this[key] = obj[key]
}
}
User.prototype.save = function (fn) {
if (this.id) {
this.update(fn);
} else {
let user = this;
db.incr('user:ids', function (err, id) {
if (err) {
return fn(err);
}
user.id = id;
user.hashPassword(function (err) {
if (err) {
return fn(err);
}
user.update(fn);
})
})
}
};
User.prototype.update = function (fn) {
let user = this;
let id = user.id;
db.set('user:id:' + user.name, id, function (err) {
if (err) {
return fn(err);
}
db.hmset('user:' + id, user, function (err) {
fn(err);
});
});
};
User.prototype.hashPassword = function (fn) {
let user = this;
bcrypt.genSalt(12, function (err, salt) {
if (err) {
return fn(err);
}
user.salt = salt;
bcrypt.hash(user.pass, salt, function (err, hash) {
if (err) {
return fn(err);
}
user.pass = hash;
fn();
});
});
};
JSON.parse(JSON.stringify(data))
can remove the function attributes in the data (don’t underestimate it! It’s fast!).