55 lines
1.1 KiB
TypeScript
Raw Normal View History

2017-11-01 19:33:08 +09:00
/**
* Module dependencies
*/
2018-04-24 18:13:06 +09:00
import $ from 'cafy'; import ID from '../../../../cafy-id';
2018-03-29 20:32:18 +09:00
import Channel from '../../../../models/channel';
import Watching from '../../../../models/channel-watching';
2017-11-01 19:33:08 +09:00
/**
* Watch a channel
*/
module.exports = (params, user) => new Promise(async (res, rej) => {
2018-03-29 14:48:47 +09:00
// Get 'channelId' parameter
2018-05-02 18:06:16 +09:00
const [channelId, channelIdErr] = $.type(ID).get(params.channelId);
2018-03-29 14:48:47 +09:00
if (channelIdErr) return rej('invalid channelId param');
2017-11-01 19:33:08 +09:00
//#region Fetch channel
const channel = await Channel.findOne({
_id: channelId
});
if (channel === null) {
return rej('channel not found');
}
//#endregion
//#region Check whether already watching
const exist = await Watching.findOne({
2018-03-29 14:48:47 +09:00
userId: user._id,
channelId: channel._id,
deletedAt: { $exists: false }
2017-11-01 19:33:08 +09:00
});
if (exist !== null) {
return rej('already watching');
}
//#endregion
// Create Watching
await Watching.insert({
2018-03-29 14:48:47 +09:00
createdAt: new Date(),
userId: user._id,
channelId: channel._id
2017-11-01 19:33:08 +09:00
});
// Send response
res();
// Increment watching count
Channel.update(channel._id, {
$inc: {
2018-03-29 14:48:47 +09:00
watchingCount: 1
2017-11-01 19:33:08 +09:00
}
});
});