forked from ng-book/angular2-rxjs-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.service.ts
78 lines (64 loc) · 2.61 KB
/
threads.service.ts
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject, Observable } from 'rxjs';
import { Thread } from './thread.model';
import { Message } from '../message/message.model';
import { MessagesService } from '../message/messages.service';
import * as _ from 'lodash';
@Injectable()
export class ThreadsService {
// `threads` is a observable that contains the most up to date list of threads
threads: Observable<{ [key: string]: Thread }>;
// `orderedThreads` contains a newest-first chronological list of threads
orderedThreads: Observable<Thread[]>;
// `currentThread` contains the currently selected thread
currentThread: Subject<Thread> =
new BehaviorSubject<Thread>(new Thread());
// `currentThreadMessages` contains the set of messages for the currently
// selected thread
currentThreadMessages: Observable<Message[]>;
constructor(public messagesService: MessagesService) {
this.threads = messagesService.messages
.map( (messages: Message[]) => {
const threads: {[key: string]: Thread} = {};
// Store the message's thread in our accumulator `threads`
messages.map((message: Message) => {
threads[message.thread.id] = threads[message.thread.id] ||
message.thread;
// Cache the most recent message for each thread
const messagesThread: Thread = threads[message.thread.id];
if (!messagesThread.lastMessage ||
messagesThread.lastMessage.sentAt < message.sentAt) {
messagesThread.lastMessage = message;
}
});
return threads;
});
this.orderedThreads = this.threads
.map((threadGroups: { [key: string]: Thread }) => {
const threads: Thread[] = _.values(threadGroups);
return _.sortBy(threads, (t: Thread) => t.lastMessage.sentAt).reverse();
});
this.currentThreadMessages = this.currentThread
.combineLatest(messagesService.messages,
(currentThread: Thread, messages: Message[]) => {
if (currentThread && messages.length > 0) {
return _.chain(messages)
.filter((message: Message) =>
(message.thread.id === currentThread.id))
.map((message: Message) => {
message.isRead = true;
return message; })
.value();
} else {
return [];
}
});
this.currentThread.subscribe(this.messagesService.markThreadAsRead);
}
setCurrentThread(newThread: Thread): void {
this.currentThread.next(newThread);
}
}
export const threadsServiceInjectables: Array<any> = [
ThreadsService
];