gpt4 book ai didi

node.js - 在没有存储的情况下在 Sequelize 中创建模型属性

转载 作者:行者123 更新时间:2023-12-03 22:29:03 24 4
gpt4 key购买 nike

我使用 Sequelize 作为我的 ORM。我想创建一个模型,其属性没有关联的存储(即没有相应的表列)。这些属性可能有 getter 和 setter,也可能有验证。

如何在 .save() 上创建不会存储到光盘的实例级属性?

场景

我有一个 LocalLogins 模型。我的模型有一个 username 、一个 salt 、一个加盐的 password 和一个未加盐的 rawPassword 。每次设置 password 时,都会对值进行加盐和散列。散列的结果成为新密码。原始“原始”值保存到 rawPassword

我不想存储未加盐的 rawPassword ,但是只要调用 .save() ,它就会用于验证。这允许模型需要一定强度的密码。

尝试

我尝试将字段设置为 '' 不幸的是没有效果。

var LocalLogin = sequelize.define('LocalLogin', {
username: {
allowNull: false,
field: 'username',
type: DataTypes.STRING,
},
password: {
allowNull: false,
field: 'password',
type: DataTypes.STRING,
},
rawPassword: {
field: '',
type: DataTypes.STRING
},
salt: {
allowNull: false,
defaultValue: function() {
var buf = crypto.randomBytes(32);
return buf.toString('hex');
},
field: 'salt',
type: DataTypes.STRING,
}
}, {
getterMethods: {
password: function() { return undefined; },
rawPassword: function() { return undefined; },
salt: function() { return undefined; }
},
setterMethods: {
password: function(val) {
// Salt and hash the password
this.setDataValue('rawPassword', val);
if(typeof val === 'string')
this.setDataValue('password', hash(val + this.getDataValue('selt')));
},
salt: function(val) {
// Salt cannot be modified
return null;
}
},
validate: {
passwordCheck: function() {
// Has a new password been set?
if(this.getDataValue('rawPassword') == null)
return

// Did they try to set the password as something other than a string?
if(typeof this.getDataValue('rawPassword') !== 'string')
throw new Error('Password must be a string');

// Make sure the password is long enough
if(this.getDataValue('rawPassword').length < 6)
throw new Error('Password must be longer than six characters.');
}
}
});

最佳答案

有一个 DataType.VIRTUAL 就是这样做的:http://docs.sequelizejs.com/en/latest/api/datatypes/#virtual

关于node.js - 在没有存储的情况下在 Sequelize 中创建模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30130856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com