summaryrefslogtreecommitdiff
path: root/src/post/create.ts
blob: ecea37382dd5e72dc4f1abc03e283eba8b113099 (plain)
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
import parseAcct from '../acct/parse';
import Post from '../models/post';
import User from '../models/user';

export default async (post, reply, repost, atMentions) => {
	post.mentions = [];

	function addMention(mentionee) {
		// Reject if already added
		if (post.mentions.some(x => x.equals(mentionee))) return;

		// Add mention
		post.mentions.push(mentionee);
	}

	if (reply) {
		// Add mention
		addMention(reply.userId);
		post.replyId = reply._id;
		post._reply = { userId: reply.userId };
	} else {
		post.replyId = null;
		post._reply = null;
	}

	if (repost) {
		if (post.text) {
			// Add mention
			addMention(repost.userId);
		}

		post.repostId = repost._id;
		post._repost = { userId: repost.userId };
	} else {
		post.repostId = null;
		post._repost = null;
	}

	await Promise.all(atMentions.map(async mention => {
		// Fetch mentioned user
		// SELECT _id
		const { _id } = await User
			.findOne(parseAcct(mention), { _id: true });

		// Add mention
		addMention(_id);
	}));

	return Post.insert(post);
};