summaryrefslogtreecommitdiff
path: root/src/models/user-list.ts
blob: 5cfa7e4dfc3a348472c89497d564bd41d3a122bd (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
import * as mongo from 'mongodb';
const deepcopy = require('deepcopy');
import db from '../db/mongodb';

const UserList = db.get<IUserList>('userList');
export default UserList;

export interface IUserList {
	_id: mongo.ObjectID;
	createdAt: Date;
	title: string;
	userId: mongo.ObjectID;
	userIds: mongo.ObjectID[];
}

/**
 * UserListを物理削除します
 */
export async function deleteUserList(userList: string | mongo.ObjectID | IUserList) {
	let u: IUserList;

	// Populate
	if (mongo.ObjectID.prototype.isPrototypeOf(userList)) {
		u = await UserList.findOne({
			_id: userList
		});
	} else if (typeof userList === 'string') {
		u = await UserList.findOne({
			_id: new mongo.ObjectID(userList)
		});
	} else {
		u = userList as IUserList;
	}

	if (u == null) return;

	// このUserListを削除
	await UserList.remove({
		_id: u._id
	});
}

export const pack = (
	userList: string | mongo.ObjectID | IUserList
) => new Promise<any>(async (resolve, reject) => {
	let _userList: any;

	if (mongo.ObjectID.prototype.isPrototypeOf(userList)) {
		_userList = await UserList.findOne({
			_id: userList
		});
	} else if (typeof userList === 'string') {
		_userList = await UserList.findOne({
			_id: new mongo.ObjectID(userList)
		});
	} else {
		_userList = deepcopy(userList);
	}

	if (!_userList) throw `invalid userList arg ${userList}`;

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

	resolve(_userList);
});