Remember that Sequelize is the module who access to the database. The previous piece of code reads from the database.json which we created previously and it opens the connection. At next, we will define our model (User) and a few methods for CRUD operations:
var User = sequelize.define('users', {
username: DataTypes.STRING,
password: DataTypes.STRING
}, {
instanceMethods: {
retrieveAll: function(onSuccess, onError) {
User.findAll({}, {raw: true})
.success(onSuccess).error(onError);
},
retrieveById: function(user_id, onSuccess, onError) {
User.find({where: {id: user_id}}, {raw: true})
.success(onSuccess).error(onError);
},
add: function(onSuccess, onError) {
var username = this.username;
var password = this.password;
var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');
User.build({ username: username, password: password })
.save().success(onSuccess).error(onError);
},
updateById: function(user_id, onSuccess, onError) {
var id = user_id;
var username = this.username;
var password = this.password;
var shasum = crypto.createHash('sha1');
shasum.update(password);
password = shasum.digest('hex');
User.update({ username: username,password: password},{where: {id: id} })
.success(onSuccess).error(onError);
},
removeById: function(user_id, onSuccess, onError) {
User.destroy({where: {id: user_id}}).success(onSuccess).error(onError);
}
}
});
1869

被折叠的 条评论
为什么被折叠?



