summaryrefslogtreecommitdiff
path: root/src/server/api/models/channel.ts
blob: 9f94c5a8d15986b818f4e3fbd8aeff875e59f592 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import { IUser } from './user';
import Watching from './channel-watching';
import db from '../../../db/mongodb';

const Channel = db.get<IChannel>('channels');
export default Channel;

export type IChannel = {
	_id: mongo.ObjectID;
	createdAt: Date;
	title: string;
	userId: mongo.ObjectID;
	index: number;
	watchingCount: number;
};

/**
 * Pack a channel for API response
 *
 * @param channel target
 * @param me? serializee
 * @return response
 */
export const pack = (
	channel: string | mongo.ObjectID | IChannel,
	me?: string | mongo.ObjectID | IUser
) => new Promise<any>(async (resolve, reject) => {

	let _channel: any;

	// Populate the channel if 'channel' is ID
	if (mongo.ObjectID.prototype.isPrototypeOf(channel)) {
		_channel = await Channel.findOne({
			_id: channel
		});
	} else if (typeof channel === 'string') {
		_channel = await Channel.findOne({
			_id: new mongo.ObjectID(channel)
		});
	} else {
		_channel = deepcopy(channel);
	}

	// Rename _id to id
	_channel.id = _channel._id;
	delete _channel._id;

	// Remove needless properties
	delete _channel.userId;

	// Me
	const meId: mongo.ObjectID = me
	? mongo.ObjectID.prototype.isPrototypeOf(me)
		? me as mongo.ObjectID
		: typeof me === 'string'
			? new mongo.ObjectID(me)
			: (me as IUser)._id
	: null;

	if (me) {
		//#region Watchしているかどうか
		const watch = await Watching.findOne({
			userId: meId,
			channelId: _channel.id,
			deletedAt: { $exists: false }
		});

		_channel.isWatching = watch !== null;
		//#endregion
	}

	resolve(_channel);
});