2018-02-01 17:06:01 -06:00
|
|
|
import * as mongo from 'mongodb';
|
|
|
|
import deepcopy = require('deepcopy');
|
2018-03-29 06:32:18 -05:00
|
|
|
import db from '../db/mongodb';
|
2018-02-01 17:06:01 -06:00
|
|
|
import Reaction from './post-reaction';
|
|
|
|
import { pack as packUser } from './user';
|
2017-03-19 14:24:19 -05:00
|
|
|
|
2018-03-29 00:48:47 -05:00
|
|
|
const PostReaction = db.get<IPostReaction>('postReactions');
|
2018-04-02 11:37:43 -05:00
|
|
|
PostReaction.createIndex(['userId', 'postId'], { unique: true });
|
2018-02-01 17:06:01 -06:00
|
|
|
export default PostReaction;
|
|
|
|
|
|
|
|
export interface IPostReaction {
|
|
|
|
_id: mongo.ObjectID;
|
2018-03-29 00:48:47 -05:00
|
|
|
createdAt: Date;
|
|
|
|
postId: mongo.ObjectID;
|
|
|
|
userId: mongo.ObjectID;
|
2018-02-03 23:52:33 -06:00
|
|
|
reaction: string;
|
2018-02-01 17:06:01 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
2018-03-29 00:48:47 -05:00
|
|
|
_reaction.user = await packUser(_reaction.userId, me);
|
2018-02-01 17:06:01 -06:00
|
|
|
|
|
|
|
resolve(_reaction);
|
|
|
|
});
|