summaryrefslogtreecommitdiff
path: root/src/server/api/endpoints/channels/unwatch.ts
blob: 709313bc6e29adf623b4e06f3a627948552df82e (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
51
52
53
54
55
56
57
58
59
60
/**
 * Module dependencies
 */
import $ from 'cafy';
import Channel from '../../models/channel';
import Watching from '../../models/channel-watching';

/**
 * Unwatch a channel
 *
 * @param {any} params
 * @param {any} user
 * @return {Promise<any>}
 */
module.exports = (params, user) => new Promise(async (res, rej) => {
	// Get 'channelId' parameter
	const [channelId, channelIdErr] = $(params.channelId).id().$;
	if (channelIdErr) return rej('invalid channelId param');

	//#region Fetch channel
	const channel = await Channel.findOne({
		_id: channelId
	});

	if (channel === null) {
		return rej('channel not found');
	}
	//#endregion

	//#region Check whether not watching
	const exist = await Watching.findOne({
		userId: user._id,
		channelId: channel._id,
		deletedAt: { $exists: false }
	});

	if (exist === null) {
		return rej('already not watching');
	}
	//#endregion

	// Delete watching
	await Watching.update({
		_id: exist._id
	}, {
		$set: {
			deletedAt: new Date()
		}
	});

	// Send response
	res();

	// Decrement watching count
	Channel.update(channel._id, {
		$inc: {
			watchingCount: -1
		}
	});
});