blob: 6c76ca8f7e7ea2cbddd593295e399cfdeebe4e2f (
plain)
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
|
import { Injectable } from '@angular/core'
import { Observable } from 'rxjs'
// TODO use npm/yarn
import { dbFactory, DatabaseConnection } from 'naive-client'
import { ChatMessage } from './chat-message.model'
const wsUrl = 'ws://localhost:5001'
const httpUrl = 'http://localhost:5000'
@Injectable({
providedIn: 'root'
})
export class MessagingService {
private db: DatabaseConnection
constructor() {
this.db = dbFactory({ wsUrl, httpUrl })
}
init() {
return this.db.init()
}
async makeChatRoom(userId: string): Promise<string> {
const chatRoomId = Date.now().toString()
await this.db.write(`/chatRooms/${chatRoomId}`, {
user: 'admin',
message: `Oh no she better don't`
})
return chatRoomId
}
getChatRoom(chatRoomId: string): Observable<ChatMessage[]> {
return Observable.create(observer => {
this.db.subscribe(`/chatRooms/${chatRoomId}`, data => {
observer.next(Object.values(data))
})
})
}
sendMessage(userId: string, chatRoomId: string, message: string) {
return this.db.write(`/chatRooms/${chatRoomId}`, {
[Date.now().toString()]: {
user: userId,
message
}
})
}
}
|