-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.js
57 lines (49 loc) · 1.32 KB
/
chat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//adding new chat documents
//setting up a real-time listener to get new chats
//update te username
//updating the room
class Chatroom{
constructor(room,username){
this.room=room;
this.username=username;
this.chats = db.collection('chats');
this.unsubscribe;
}
async addChat(message){
//format char object
const now = new Date();
const chat = {
message:message,
username:this.username,
room:this.room,
created_at: firebase.firestore.Timestamp.fromDate(now)
};
//save the chat document
const response = await this.chats.add(chat);
return response;
}
getChats(callback){
this.unsubscribe = this.chats
.where('room','==',this.room)
.orderBy('created_at')
.onSnapshot(snapshot=>{
snapshot.docChanges().forEach(change=>{
if(change.type==='added'){
//update ui
callback(change.doc.data());
}
});
});
}
updateName(username){
this.username=username;
localStorage.setItem('username',username)
}
updateRoom(room){
this.room = room;
console.log('room updated')
if(this.unsubscribe){
this.unsubscribe()
}
}
}