summaryrefslogtreecommitdiff
path: root/sample-apps/angular-chat/src/app/messaging.service.ts
blob: 40e2728d61aa530236b9657238e2954027377d3a (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
51
52
53
import { Injectable } from '@angular/core'
import { Observable, pipe } from 'rxjs'
import { map, tap } from 'rxjs/operators'

import { NaiveService } from './naive.service'
import { ChatMessage } from './chat-message.model'

@Injectable({
  providedIn: 'root'
})
export class MessagingService {
  constructor(private db: NaiveService) {}

  init() {
    return this.db.init()
  }

  async makeChatRoom(): Promise<string> {
    const chatRoomId = `chatRoom-${Date.now().toString()}`
    await this.pushToDirectory(chatRoomId)
    await this.pushToChatRoom('admin', chatRoomId, 'oh hey')
    return chatRoomId
  }

  // TODO this is broken because of how path matching
  // is implemented
  getDirectory(): Observable<string[]> {
    return this.db.toObservable(`/directory`).pipe(map(Object.keys))
  }

  getChatRoom(chatRoomId: string): Observable<ChatMessage[]> {
    return this.db
      .toObservable(`/chatRooms/${chatRoomId}`)
      .pipe(map(Object.values))
  }

  sendMessage(userId: string, chatRoomId: string, message: string) {
    return this.pushToChatRoom(userId, chatRoomId, message)
  }

  private pushToDirectory(chatRoomId: string) {
    return this.db.write(`/directory/${chatRoomId}`, { created: Date.now() })
  }

  private pushToChatRoom(userId: string, chatRoomId: string, message: string) {
    return this.db.write(`/chatRooms/${chatRoomId}`, {
      [Date.now().toString()]: {
        user: userId,
        message
      }
    })
  }
}