-
Notifications
You must be signed in to change notification settings - Fork 73
/
new-chat.ts
114 lines (99 loc) · 2.86 KB
/
new-chat.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { Component, OnInit } from '@angular/core';
import { AlertController, ViewController } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { _ } from 'meteor/underscore';
import { Observable, Subscription, BehaviorSubject } from 'rxjs';
import { Chats, Pictures, Users } from '../../../../imports/collections';
import { User } from '../../../../imports/models';
import template from './new-chat.html';
@Component({
template
})
export class NewChatComponent implements OnInit {
searchPattern: BehaviorSubject<any>;
senderId: string;
users: Observable<User[]>;
usersSubscription: Subscription;
constructor(
private alertCtrl: AlertController,
private viewCtrl: ViewController
) {
this.senderId = Meteor.userId();
this.searchPattern = new BehaviorSubject(undefined);
}
ngOnInit() {
this.observeSearchBar();
}
updateSubscription(newValue) {
this.searchPattern.next(newValue);
}
observeSearchBar(): void {
this.searchPattern.asObservable()
// Prevents the search bar from being spammed
.debounce(() => Observable.timer(1000))
.forEach(() => {
if (this.usersSubscription) {
this.usersSubscription.unsubscribe();
}
this.usersSubscription = this.subscribeUsers();
});
}
addChat(user): void {
MeteorObservable.call('addChat', user._id).subscribe({
next: () => {
this.viewCtrl.dismiss();
},
error: (e: Error) => {
this.viewCtrl.dismiss().then(() => {
this.handleError(e);
});
}
});
}
subscribeUsers(): Subscription {
// Fetch all users matching search pattern
const subscription = MeteorObservable.subscribe('users', this.searchPattern.getValue());
const autorun = MeteorObservable.autorun();
return Observable.merge(subscription, autorun).subscribe(() => {
this.users = this.findUsers();
});
}
findUsers(): Observable<User[]> {
// Find all belonging chats
return Chats.find({
memberIds: this.senderId
}, {
fields: {
memberIds: 1
}
})
// Invoke merge-map with an empty array in case no chat found
.startWith([])
.mergeMap((chats) => {
// Get all userIDs who we're chatting with
const receiverIds = _.chain(chats)
.pluck('memberIds')
.flatten()
.concat(this.senderId)
.value();
// Find all users which are not in belonging chats
return Users.find({
_id: { $nin: receiverIds }
})
// Invoke map with an empty array in case no user found
.startWith([]);
});
}
handleError(e: Error): void {
console.error(e);
const alert = this.alertCtrl.create({
buttons: ['OK'],
message: e.message,
title: 'Oops!'
});
alert.present();
}
getPic(pictureId): string {
return Pictures.getPictureUrl(pictureId);
}
}