aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/live/live-quota-store.ts
blob: 44539faaa39066301b519f458e10d9ec8f54f660 (plain) (blame)
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
class LiveQuotaStore {

  private static instance: LiveQuotaStore

  private readonly livesPerUser = new Map<number, { sessionId: string, size: number }[]>()

  private constructor () {
  }

  addNewLive (userId: number, sessionId: string) {
    if (!this.livesPerUser.has(userId)) {
      this.livesPerUser.set(userId, [])
    }

    const currentUserLive = { sessionId, size: 0 }
    const livesOfUser = this.livesPerUser.get(userId)
    livesOfUser.push(currentUserLive)
  }

  removeLive (userId: number, sessionId: string) {
    const newLivesPerUser = this.livesPerUser.get(userId)
                                             .filter(o => o.sessionId !== sessionId)

    this.livesPerUser.set(userId, newLivesPerUser)
  }

  addQuotaTo (userId: number, sessionId: string, size: number) {
    const lives = this.livesPerUser.get(userId)
    const live = lives.find(l => l.sessionId === sessionId)

    live.size += size
  }

  getLiveQuotaOf (userId: number) {
    const currentLives = this.livesPerUser.get(userId)
    if (!currentLives) return 0

    return currentLives.reduce((sum, obj) => sum + obj.size, 0)
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}

export {
  LiveQuotaStore
}