【问题标题】:Prevent firebase function from overwriting existing data防止 firebase 功能覆盖现有数据
【发布时间】:2020-07-02 05:37:29
【问题描述】:

出于几个原因,我正在将在我的应用程序中创建用户的过程转移到 firebase 函数,但我遇到了一个问题:

我有一个 /users ref 和一个 /usernames,当创建一个用户时,我将他们的信息保存在用户和用户名中(可公开访问以查看用户名是否可用)作为事务,因此用户名会立即添加创建了一个用户,并且我的安全规则防止覆盖现有数据。

但是,通过 firebase 功能,这些安全规则会被绕过,因此可能会出现 2 个用户使用相同的用户名注册并且一个人的数据将被另一个人覆盖的情况

有没有办法防止覆盖云函数中的现有数据? (最好不要让他们通过安全规则)

【问题讨论】:

    标签: firebase firebase-realtime-database


    【解决方案1】:

    我遇到了类似的问题,我发现最好的解决方案是使用 firebase 提供的事务方法。

    假设你有一个用户名 ref,你可以这样做:

    db.ref('usernames').child(theUsername).transaction(function (usernameInfo) {
        if (usernameInfo === null) {
            return {
                ...anObjectOfUserData // or could just return true
            }
        }
    
        // if the data is not null it means the username is used 
        // returning nothing makes the transaction do no updates
        return 
    }, function (error, isComitted, snap) {
       //
       // Use isCommitted from the onComplete function to determine if data was commited 
       // DO NOT USE the onUpdate function to do this as it will almost certainly run a couple of times
       //
    })
    

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多