-
Notifications
You must be signed in to change notification settings - Fork 185
/
methods.ts
98 lines (80 loc) · 2.49 KB
/
methods.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
import { Chats } from './collections/chats';
import { Messages } from './collections/messages';
import { MessageType, Profile } from './models';
import { check, Match } from 'meteor/check';
const nonEmptyString = Match.Where((str) => {
check(str, String);
return str.length > 0;
});
Meteor.methods({
addChat(receiverId: string): void {
if (!this.userId) {
throw new Meteor.Error('unauthorized',
'User must be logged-in to create a new chat');
}
check(receiverId, nonEmptyString);
if (receiverId === this.userId) {
throw new Meteor.Error('illegal-receiver',
'Receiver must be different than the current logged in user');
}
const chatExists = !!Chats.collection.find({
memberIds: { $all: [this.userId, receiverId] }
}).count();
if (chatExists) {
throw new Meteor.Error('chat-exists',
'Chat already exists');
}
const chat = {
memberIds: [this.userId, receiverId]
};
Chats.insert(chat);
},
removeChat(chatId: string): void {
if (!this.userId) {
throw new Meteor.Error('unauthorized',
'User must be logged-in to remove chat');
}
check(chatId, nonEmptyString);
const chatExists = !!Chats.collection.find(chatId).count();
if (!chatExists) {
throw new Meteor.Error('chat-not-exists',
'Chat doesn\'t exist');
}
Chats.remove(chatId);
},
updateProfile(profile: Profile): void {
if (!this.userId) throw new Meteor.Error('unauthorized',
'User must be logged-in to create a new chat');
check(profile, {
name: nonEmptyString,
pictureId: Match.Maybe(nonEmptyString)
});
Meteor.users.update(this.userId, {
$set: {profile}
});
},
addMessage(type: MessageType, chatId: string, content: string) {
if (!this.userId) throw new Meteor.Error('unauthorized',
'User must be logged-in to create a new chat');
check(type, Match.OneOf(String, [ MessageType.TEXT, MessageType.LOCATION ]));
check(chatId, nonEmptyString);
check(content, nonEmptyString);
const chatExists = !!Chats.collection.find(chatId).count();
if (!chatExists) {
throw new Meteor.Error('chat-not-exists',
'Chat doesn\'t exist');
}
return {
messageId: Messages.collection.insert({
chatId: chatId,
senderId: this.userId,
content: content,
createdAt: new Date(),
type: type
})
};
},
countMessages(): number {
return Messages.collection.find().count();
}
});