summaryrefslogtreecommitdiff
path: root/src/models/note-reaction.ts
blob: 915dc0cf91fdc4b657580a860e3ca5519bcb5cf1 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import * as mongo from 'mongodb';
import $ from 'cafy';
const deepcopy = require('deepcopy');
import db from '../db/mongodb';
import Reaction from './note-reaction';
import { pack as packUser } from './user';

const NoteReaction = db.get<INoteReaction>('noteReactions');
NoteReaction.createIndex(['userId', 'noteId'], { unique: true });
export default NoteReaction;

export interface INoteReaction {
	_id: mongo.ObjectID;
	createdAt: Date;
	noteId: mongo.ObjectID;
	userId: mongo.ObjectID;
	reaction: string;
}

export const validateReaction = $.str.or([
	'like',
	'love',
	'laugh',
	'hmm',
	'surprise',
	'congrats',
	'angry',
	'confused',
	'pudding'
]);

/**
 * NoteReactionを物理削除します
 */
export async function deleteNoteReaction(noteReaction: string | mongo.ObjectID | INoteReaction) {
	let n: INoteReaction;

	// Populate
	if (mongo.ObjectID.prototype.isPrototypeOf(noteReaction)) {
		n = await NoteReaction.findOne({
			_id: noteReaction
		});
	} else if (typeof noteReaction === 'string') {
		n = await NoteReaction.findOne({
			_id: new mongo.ObjectID(noteReaction)
		});
	} else {
		n = noteReaction as INoteReaction;
	}

	if (n == null) return;

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

/**
 * Pack a reaction for API response
 */
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.userId, me);

	resolve(_reaction);
});