標籤 Firebase 下的所有文章

firebase客服聊天實作[JavaScript]

這是第一次使用firebase實作所以就順便記錄一下

有興趣可以參考看看!

首先先做client端

先建立一個client端的firebase物件

var clientRef = new Firebase('https://test.firebaseio.com/client/'+chat_unique);

這裡的chat_unique是一個維一值用來記錄儲存客戶端資料

接著只要監聽在輸入欄位所送出的資料

clientRef.push({id: id, text: text, server: false});

這邊說明一下我所存的欄位有那些

id用來記錄用戶端id

text用來記錄用戶端輸入字串

server用來記錄是否為客服

在來就是監聽clientRef的變化所需要做的處理

clientRef.on('child_added', function(snapshot) {
    var message = snapshot.val();

    if(message.server){
        $('.server_msg').append(message.text);
    }else{
        $('.client_msg').append(message.text);
    }
});

這樣客戶端基本上就算完成了

在來就是一對多的server端了

先建立一個server端的firebase物件

serverRef = new Firebase('https://test.firebaseio.com/client');

然後監聽serverRef的變化做處理

serverRef.on('child_added', function(childSnapshot, prevChildName) {
    var childname = childSnapshot.name();//取得節點名稱
    var clientRef = new Firebase('https://test.firebaseio.com/client/'+childname);//建立新的clinet物件

    //接著跟client端一樣只要監聽在輸入欄位所送出的資料
    clientRef.push({id: id, text: text, server: true});

    //監聽clientRef的變化做處理
    clientRef.on('child_added', function(snapshot) {
        var message = snapshot.val();

        if(message.server){
            $('.server_msg').append(message.text);
        }else{
            $('.client_msg').append(message.text);
        }
    });
});

這樣就差不多了

這邊可能會有的問題是在server欄位需要做權限的設定

只能讓server端寫入true

所以在firebase的資料庫規則裡寫下

{
  "rules": {
    ".read": "auth.username == 'admin'",
    ".write": "auth.username == 'admin'",
    "login":{
      ".read":  true,
      ".write":   "auth.username == 'admin'"
    },
    "service":{
      "$user": {
        ".read": true,
        "$other":{
          ".read": true,
          ".write": "newData.child('admin').val() == false"
        }
      }
    }
  }
}

這樣基本上就差不多了在來就只剩美化和一些細節處理