在link的回答中,为了保持用户数量,它会消耗:当客户端在该函数的承诺中创建用户以返回更新计数的事务时。
以下是firebase 3.0中的类似代码段
数据库结构是:
- users
-- someuid
--- displayName: 'Dale'
- usersCount
-- count: 1
-- users
--- someuid : true
<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js">
</script>
<script>
// Initialize Firebase
var config = {
..
};
firebase.initializeApp(config);
function createNewAccount() {
return firebase.auth().signInAnonymously()
.then(createUserAccountData)
.then(updateUser);
}
function updateUser() {
console.log('update user count');
var user = firebase.auth().currentUser;
var ref = firebase.database().ref('/usersCount');
var uid = user.uid;
return ref.transaction(function(post) {
if(post) {
if(post.users && post.users[uid]) {
} else {
post.count++;
if(!post.users) {
post.users = {};
}
post.users[uid] = true;
}
}
return post;
})
}
/**
* @return {User|fasle}
*/
function getUserObjectForDb (user) {
console.log('get user obj');
if(!user) return false;
return {
displayName: user.displayName || user.uid || false,
email: user.email || false,
arbitraryData: 'foo'
}
}
/**
* Create a user account given a firebase user object.
* @param {Object} result
*/
function createUserAccountData(result) {
console.log('create user account data');
var uid = result && result.uid || false
if(!uid) return false;
var user = getUserObjectForDb(result);
var path = 'users/' + uid;
var ref = firebase.database().ref(path);
return ref.set(user);
}
</script>
<button onclick="createNewAccount()">Create new account</button>
用户使用firebas.auth创建一个帐户 然后,事务将用户详细信息添加到用户并递增usersCount
如何使这样的事情变得安全。 如何才能信任客户更新计数器?