summaryrefslogtreecommitdiff
path: root/src/api/serializers/notification.ts
blob: ac919dc8b0b330e4410ba141ac02a87f3d9234ae (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
/**
 * Module dependencies
 */
import * as mongo from 'mongodb';
import Notification from '../models/notification';
import serializeUser from './user';
import serializePost from './post';
import deepcopy = require('deepcopy');

/**
 * Serialize a notification
 *
 * @param {any} notification
 * @return {Promise<any>}
 */
export default (notification: any) => new Promise<any>(async (resolve, reject) => {
	let _notification: any;

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

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

	// Rename notifier_id to user_id
	_notification.user_id = _notification.notifier_id;
	delete _notification.notifier_id;

	const me = _notification.notifiee_id;
	delete _notification.notifiee_id;

	// Populate notifier
	_notification.user = await serializeUser(_notification.user_id, me);

	switch (_notification.type) {
		case 'follow':
			// nope
			break;
		case 'mention':
		case 'reply':
		case 'repost':
		case 'quote':
		case 'reaction':
		case 'poll_vote':
			// Populate post
			_notification.post = await serializePost(_notification.post_id, me);
			break;
		default:
			console.error(`Unknown type: ${_notification.type}`);
			break;
	}

	resolve(_notification);
});