Ret*_*sam 4 transactions atomic firebase firebase-realtime-database
我正在考虑使用firebase作为Web应用程序用户数据的数据存储.我目前的想法是使用他们加入的时间戳作为引用该用户数据的密钥来存储每个用户的数据.这种方案的优点在于它是一种为用户分配唯一整数ID的简单方法,并且可以简化用户的时间顺序排序.
然而,缺点是如果两个"添加用户"请求被提交相同的数据,应用程序将很乐意添加两个单独的条目,这是不理想的.我可以随意乱扔东西(我开始认为我应该使用电子邮件作为密钥并通过连接数据优先考虑,而不是我当前的方案),但我想我不想这样做.有没有办法防止重复数据?
天真的方法可能只是做以下事情:
if(!searchFirebaseForUser(data)) {
addUser(data);
}
Run Code Online (Sandbox Code Playgroud)
但这绝对是一种竞争条件; 两个请求都很容易查询并在数据库中找不到用户,并且都添加.我想在一个交易中执行此操作,但似乎Firebase事务支持不包括这种情况.有办法处理这个吗?
您可能必须使用用户名或电子邮件地址作为密钥,并尝试以原子方式写入该位置.
以下是来自事务函数引用的相关代码示例.在这种情况下,我们将其wilma用作用户的密钥.
// Try to create a user for wilma, but only if the user id 'wilma' isn't already taken.
var wilmaRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/wilma');
wilmaRef.transaction(function(currentData) {
if (currentData === null) {
return {name: {first: 'Wilma', last: 'Flintstone'} };
} else {
console.log('User wilma already exists.');
return; // Abort the transaction.
}
}, function(error, committed, snapshot) {
if (error)
console.log('Transaction failed abnormally!', error);
else if (!committed)
console.log('We aborted the transaction (because wilma already exists).');
else
console.log('User wilma added!');
console.log('Wilma\'s data: ', snapshot.val());
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9722 次 |
| 最近记录: |