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
115
116
117
118
119
120
121
122
|
/**
* Module dependencies
*/
import $ from 'cafy';
import Reaction from '../../../models/post-reaction';
import Post, { pack as packPost } from '../../../models/post';
import { pack as packUser } from '../../../models/user';
import Watching from '../../../models/post-watching';
import notify from '../../../common/notify';
import watch from '../../../common/watch-post';
import { publishPostStream, pushSw } from '../../../event';
/**
* React to a post
*
* @param {any} params
* @param {any} user
* @return {Promise<any>}
*/
module.exports = (params, user) => new Promise(async (res, rej) => {
// Get 'postId' parameter
const [postId, postIdErr] = $(params.postId).id().$;
if (postIdErr) return rej('invalid postId param');
// Get 'reaction' parameter
const [reaction, reactionErr] = $(params.reaction).string().or([
'like',
'love',
'laugh',
'hmm',
'surprise',
'congrats',
'angry',
'confused',
'pudding'
]).$;
if (reactionErr) return rej('invalid reaction param');
// Fetch reactee
const post = await Post.findOne({
_id: postId
});
if (post === null) {
return rej('post not found');
}
// Myself
if (post.userId.equals(user._id)) {
return rej('cannot react to my post');
}
// if already reacted
const exist = await Reaction.findOne({
postId: post._id,
userId: user._id,
deletedAt: { $exists: false }
});
if (exist !== null) {
return rej('already reacted');
}
// Create reaction
await Reaction.insert({
createdAt: new Date(),
postId: post._id,
userId: user._id,
reaction: reaction
});
// Send response
res();
const inc = {};
inc[`reaction_counts.${reaction}`] = 1;
// Increment reactions count
await Post.update({ _id: post._id }, {
$inc: inc
});
publishPostStream(post._id, 'reacted');
// Notify
notify(post.userId, user._id, 'reaction', {
postId: post._id,
reaction: reaction
});
pushSw(post.userId, 'reaction', {
user: await packUser(user, post.userId),
post: await packPost(post, post.userId),
reaction: reaction
});
// Fetch watchers
Watching
.find({
postId: post._id,
userId: { $ne: user._id },
// 削除されたドキュメントは除く
deletedAt: { $exists: false }
}, {
fields: {
userId: true
}
})
.then(watchers => {
watchers.forEach(watcher => {
notify(watcher.userId, user._id, 'reaction', {
postId: post._id,
reaction: reaction
});
});
});
// この投稿をWatchする
if (user.account.settings.auto_watch !== false) {
watch(user._id, post);
}
});
|