summaryrefslogtreecommitdiff
path: root/src/api/models/post-reaction.ts
blob: 639a70e006b595c18aa4febb2e719af765aa112e (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
import * as mongo from 'mongodb';
import deepcopy = require('deepcopy');
import db from '../../db/mongodb';
import Reaction from './post-reaction';
import { pack as packUser } from './user';

const PostReaction = db.get<IPostReaction>('post_reactions');
export default PostReaction;

export interface IPostReaction {
	_id: mongo.ObjectID;
	created_at: Date;
	deleted_at: Date;
	reaction: string;
}

/**
 * Pack a reaction for API response
 *
 * @param {any} reaction
 * @param {any} me?
 * @return {Promise<any>}
 */
export const pack = (
	reaction: any,
	me?: any
) => new Promise<any>(async (resolve, reject) => {
	let _reaction: any;

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

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

	// Populate user
	_reaction.user = await packUser(_reaction.user_id, me);

	resolve(_reaction);
});