2017-10-30 01:30:32 -07:00
|
|
|
import * as mongo from 'mongodb';
|
2018-02-01 15:06:01 -08:00
|
|
|
import deepcopy = require('deepcopy');
|
|
|
|
import { IUser } from './user';
|
|
|
|
import Watching from './channel-watching';
|
2018-03-28 09:20:40 -07:00
|
|
|
import db from '../../../db/mongodb';
|
2017-10-30 01:30:32 -07:00
|
|
|
|
2018-02-01 15:06:01 -08:00
|
|
|
const Channel = db.get<IChannel>('channels');
|
|
|
|
export default Channel;
|
2017-10-30 01:30:32 -07:00
|
|
|
|
2017-10-31 05:42:11 -07:00
|
|
|
export type IChannel = {
|
2017-10-30 01:30:32 -07:00
|
|
|
_id: mongo.ObjectID;
|
2018-03-28 22:48:47 -07:00
|
|
|
createdAt: Date;
|
2017-10-30 01:30:32 -07:00
|
|
|
title: string;
|
2018-03-28 22:48:47 -07:00
|
|
|
userId: mongo.ObjectID;
|
2017-10-31 09:38:19 -07:00
|
|
|
index: number;
|
2018-03-28 22:48:47 -07:00
|
|
|
watchingCount: number;
|
2017-10-30 01:30:32 -07:00
|
|
|
};
|
2018-02-01 15:06:01 -08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
2018-03-28 22:48:47 -07:00
|
|
|
delete _channel.userId;
|
2018-02-01 15:06:01 -08:00
|
|
|
|
|
|
|
// 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({
|
2018-03-28 22:48:47 -07:00
|
|
|
userId: meId,
|
|
|
|
channelId: _channel.id,
|
|
|
|
deletedAt: { $exists: false }
|
2018-02-01 15:06:01 -08:00
|
|
|
});
|
|
|
|
|
2018-03-28 22:48:47 -07:00
|
|
|
_channel.isWatching = watch !== null;
|
2018-02-01 15:06:01 -08:00
|
|
|
//#endregion
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve(_channel);
|
|
|
|
});
|