高频调用导致 Waterline & Sails 中的 findOrCreate 重复
High frequency calls leads to duplicates with findOrCreate in Waterline & Sails
如何在 Sails 中使用 Waterline 处理 Postgresql 数据库的高频更新或创建请求?
我尝试使用 findOrCreate 然后更新项目,我尝试使用 findOne 然后更新或创建项目,我尝试放置 beforeCreate、beforeValidation 挂钩方法来检查项目是否存在但没有成功。
我是否应该添加错误处理程序以从唯一索引中获取错误并重试?
在Waterline docs中,有一个关于它的警告,但没有解决这个问题的方向。
感谢您的任何提示。
Should I add an error handler to get errors from the unique index and try again?
在 Waterline 实施交易之前,这将是唯一的选择。类似于:
// This will hold the found or created user
var user;
// Keep repeating until we find or create a user, or get an error we dont expect
async.doUntil(
function findOrCreate(cb) {
// Try findOrCreate
User.findOrCreate(criteria, values).exec(function(err, _user) {
// If we get an error that is not a uniqueness error on the
// attribute we expect collisions on, bail out of the doUntil
if (err &&
(
!err.invalidAttributes["myUniqueAttribute"] ||
!_.find(err.invalidAttributes["myUniqueAttribute"], {rule: 'unique'})
)
) {
return cb(err);
}
// Otherwise set the user var
// It may still be undefined if a uniqueness error occurred;
// this will just cause doUntil to run this function again
else {
user = _user;
return cb();
}
},
// If we have a user, we are done. Otherwise go again.
function test() {return user},
// We are done!
function done(err) {
if (err) {return res.serverError(err);}
// "user" now contains the found or created user
}
});
不是最漂亮的,但应该可以了。
如何在 Sails 中使用 Waterline 处理 Postgresql 数据库的高频更新或创建请求?
我尝试使用 findOrCreate 然后更新项目,我尝试使用 findOne 然后更新或创建项目,我尝试放置 beforeCreate、beforeValidation 挂钩方法来检查项目是否存在但没有成功。 我是否应该添加错误处理程序以从唯一索引中获取错误并重试?
在Waterline docs中,有一个关于它的警告,但没有解决这个问题的方向。
感谢您的任何提示。
Should I add an error handler to get errors from the unique index and try again?
在 Waterline 实施交易之前,这将是唯一的选择。类似于:
// This will hold the found or created user
var user;
// Keep repeating until we find or create a user, or get an error we dont expect
async.doUntil(
function findOrCreate(cb) {
// Try findOrCreate
User.findOrCreate(criteria, values).exec(function(err, _user) {
// If we get an error that is not a uniqueness error on the
// attribute we expect collisions on, bail out of the doUntil
if (err &&
(
!err.invalidAttributes["myUniqueAttribute"] ||
!_.find(err.invalidAttributes["myUniqueAttribute"], {rule: 'unique'})
)
) {
return cb(err);
}
// Otherwise set the user var
// It may still be undefined if a uniqueness error occurred;
// this will just cause doUntil to run this function again
else {
user = _user;
return cb();
}
},
// If we have a user, we are done. Otherwise go again.
function test() {return user},
// We are done!
function done(err) {
if (err) {return res.serverError(err);}
// "user" now contains the found or created user
}
});
不是最漂亮的,但应该可以了。