How to store users and groups for a chat using Firebase

后端 未结 1 780
花落未央
花落未央 2021-01-03 02:53

I would like to make a chat using Firebase. I need to display for each users the list of group they belong to and also for each group all the members.

Because of ho

相关标签:
1条回答
  • 2021-01-03 03:19

    The data model you have proposed is consistent with recommendations for firebase. A more detailed explanation is outlined in best way to structure data in firebase

    users/userid/groups
    groups/groupid/users
    

    Firebase provides .transaction for atomic operations. You may chain multiple transactions to ensure data consistency. You may also use onComplete callback function. For detailed explanation refer to firebase transaction. I am using this same approach to keep multiple message counts up to date for a dashboard display.

    Sample code for nested transaction:

    ref.child('users').child(userid).child(groupid).transaction(function (currentData) {
      if (currentData === null) {
        return groupid;
      } else {
        console.log('groupid already exists.');
        return; // Abort the transaction.
      }
      }, function (error, committed, snapshot) {
        if (committed) {
          console.log('start a new transaction');
          ref.child('groups').child(groupid).child(userid).tranaction(function (currentData) {
            if (currentData === null) {
                return userid;
            } else {
                console.log('Userid already exists.');
                //add code here to roll back the groupid added to users
                return; // Abort the transaction.
            }
          }, function (error, committed, snapshot) {
             if (error) {
                 //rollback the groupid that was added to users in previous transaction
             }
          })
      }
    });
    
    0 讨论(0)
提交回复
热议问题