import uniqid from "uniqid" ; import { Comment , DiscussionParentType } from "../../types/discussion" ; import { DiscussionModel } from "../models/DiscussionModel" ; export async function getDiscussionByParent ( organization , parentType , parentId ) { return await DiscussionModel . findOne ( { organization , parentType , parentId , } ) ; } export async function getAllDiscussionsByOrg ( organization ) { return await DiscussionModel . find ( { organization , } ) ; } export async function getAllDiscussionsByOrgFromDate ( organization , date ) { return await DiscussionModel . find ( { organization , dateUpdated : { $gte : date } , } ) ; } export async function getLastNDiscussions ( organization , num ) { return await DiscussionModel . find ( { organization , } ) . sort ( { dateUpdated : - 1 } ) . limit ( num ) ; } export async function addComment ( organization , parentType , parentId , user , comment ) { const newComment = { content : comment , date : new Date ( ) , userEmail : user . email , userId : user . id , userName : user . name , } ; const discussion = await getDiscussionByParent ( organization , parentType , parentId ) ; if ( discussion && discussion . id ) { discussion . comments . push ( newComment ) ; discussion . dateUpdated = new Date ( ) ; discussion . markModified ( "comments" ) ; await discussion . save ( ) ; return ; } await DiscussionModel . create ( { id : uniqid ( "com_" ) , organization , parentType , parentId , comments : [ newComment ] , dateUpdated : new Date ( ) , } ) ; }