我正在创建一个表来存储用户会话。我将使用以下方法将IP 地址存储为整数: 存储为 int 的 IP 地址会导致溢出?
我想为 IP 字段指定一个 getter 和 setter,以便它可以在 IP 和 int 之间自动转换。
不幸的是,我收到以下错误,我不知道发生了什么。我已经尝试修复它几个小时了,谷歌没有给我任何结果:
RangeError: Maximum call stack size exceeded
模型:
model = db.define(name, {
id: {type: Sequelize.STRING, allowNull: false, primaryKey: true},
ipAddress: {type: Sequelize.INTEGER(11).UNSIGNED, allowNull: false},
userAgent: {type: Sequelize.STRING, allowNull: false},
username: {type: Sequelize.STRING, allowNull: false},
password: {type: Sequelize.STRING, allowNull: false},
firstName: {type: Sequelize.STRING, allowNull: false},
lastName: {type: Sequelize.STRING, allowNull: false},
email: {type: Sequelize.STRING}
}, {
getterMethods: {
name: function() { return this.firstName + this.lastName },
ipAddress: function() {
ip = this.getDataValue("ipAddress");
return ((ip >> 24) & 255) + "." + ((ip >> 16) & 255) + "." + ((ip >> 8) & 255) + "." + (ip & 255);
}
},
setterMethods: {
ipAddress: function(ip) {
var parts = ip.split(".");
var ret = 0;
ret += parseInt(parts[0], 10) << 24;
ret += parseInt(parts[1], 10) << 16;
ret += parseInt(parts[2], 10) << 8;
ret += parseInt(parts[3], 10);
return ret;
}
}
});
插入IP:
model.findOrCreate({id: sessionId}, {
id: sessionId,
ipAddress: req.ip, // === "192.168.1.79"
userAgent: req.get("user-agent"),
username: "test",
password: "test",
firstName: "first",
lastName: "last",
email: "email"
})
我可以确认 getter/setter 代码确实可以根据需要进行转换,但它在 Sequelize 中无法正常运行。