Skip to content

Commit

Permalink
Merge pull request #204 from SquareTable/203-make-comment-collection-…
Browse files Browse the repository at this point in the history
…and-schema

Start to use Comment collection schema
  • Loading branch information
Sebastian-Webster authored Oct 19, 2023
2 parents 24396b1 + 5e19cf3 commit e8a6cbb
Show file tree
Hide file tree
Showing 11 changed files with 3,023 additions and 4,073 deletions.
90 changes: 90 additions & 0 deletions OneTimeExecuteCode/CommentCollection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//This is the OneTimeExecuteCode for moving comments from being an array inside of a post document to being its own collection

const ImagePost = require('../models/ImagePost');
const Poll = require('../models/Poll');
const Thread = require('../models/Thread');
const Comment = require('../models/Comment');
const mongoose = require('mongoose');

//Usually we would have to implement functionality for comment replies, but as of writing this code, no comment replies have been made.
//For the sake of simplicity, comment reply transfers will be ignored (since there are none)

Promise.all([
ImagePost.find({"comments.0": {$exists: true}}).lean(),
Poll.find({"comments.0": {$exists: true}}).lean(),
Thread.find({"comments.0": {$exists: true}}).lean()
]).then(([images, polls, threads]) => {
const updates = [];

for (const image of images) {
for (const comment of image.comments) {
updates.push({
commenterId: comment.commenterId,
text: comment.commentsText,
datePosted: comment.datePosted,
postId: image._id,
postFormat: "Image",
replies: 0
})
}
}

for (const poll of polls) {
for (const comment of poll.comments) {
updates.push({
commenterId: comment.commenterId,
text: comment.commentsText,
datePosted: comment.datePosted,
postId: poll._id,
postFormat: "Poll",
replies: 0
})
}
}

for (const thread of threads) {
for (const comment of thread.comments) {
updates.push({
commenterId: comment.commenterId,
text: comment.commentsText,
datePosted: comment.datePosted,
postId: thread._id,
postFormat: "Thread",
replies: 0
})
}
}

mongoose.startSession().then(session => {
session.startTransaction();

Promise.all([
Comment.insertMany(updates, {session}),
ImagePost.updateMany({}, {$unset: {comments: ""}}, {session}),
Poll.updateMany({}, {$unset: {comments: ""}}, {session}),
Thread.updateMany({}, {$unset: {comments: ""}}, {session})
]).then(() => {
session.commitTransaction().then(() => {
session.endSession().then(() => {
console.log('Successfully transferred', updates.length, 'comments into the Comment collection!')
}).catch(error => {
console.error('An erorr occurred while ending Mongoose session:', error)
})
}).catch(error => {
console.error('An error occurred while committing comment transfer transaction:', error)
session.endSession().catch(error => {
console.error('An error occurred while ending Mongoose session:', error)
})
})
}).catch(error => {
console.error('An error occurred while making comment transfer database operations:', error)
session.endSession().catch(error => {
console.error('An error occurred while ending Mongoose session:', error)
})
})
}).catch(error => {
console.error('An error occurred while starting Mongoose session:', error)
})
}).catch(error => {
console.error('An error occurred while getting images, polls, and threads:', error)
})
1 change: 1 addition & 0 deletions constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const CONSTANTS = {
NUM_THREAD_POSTS_TO_SEND_PER_API_CALL: 10, //Used for temp/getthreadsfromprofile API - Determines how many thread posts to send per API call
NUM_CATEGORIES_TO_SEND_PER_API_CALL: 10, //Used for temp/findcategoryfromprofile, temp/getCategoriesUserIsAPartOf, and temp/searchpagesearchcategories APIs - Determines how many categories to send per API call
NUM_USERS_TO_SEND_PER_PROFILE_STATS_API_CALL: 10, //Used for temp/getProfileStats API - Determines how many users they are following or users that follow them to send per API call
COMMENT_API_ALLOWED_POST_FORMATS: ["Image", "Poll", "Thread"]
}

module.exports = CONSTANTS
6,206 changes: 2,630 additions & 3,576 deletions controllers/Temp.js

Large diffs are not rendered by default.

34 changes: 32 additions & 2 deletions libraries/Array.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
class Array {
class ArrayClass {
returnSomeItems(array, skip, limit) {
return {items: array.splice(skip, limit), noMoreItems: skip >= array.length}
}

returnOwnerPostPairs(posts, owners, ownerIdKey) {
const users = {};
for (const user of owners) {
users[String(user._id)] = user;
}

const postOwnerPairMap = new Map();
const postsWithNoOwners = [];

for (const post of posts) {
const ownerId = String(post[ownerIdKey])
const owner = users[ownerId];

if (owner) {
if (postOwnerPairMap.has(owner)) {
postOwnerPairMap.get(owner).push(post)
} else {
postOwnerPairMap.set(owner, [post])
}
} else {
postsWithNoOwners.push(post)
}
}

return {
ownerPostPairs: Array.from(postOwnerPairMap.entries()),
postsWithNoOwners
}
}
}

module.exports = Array;
module.exports = ArrayClass;
62 changes: 62 additions & 0 deletions libraries/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
const Upvote = require('../models/Upvote')
const Downvote = require('../models/Downvote')

class CommentLibrary {
processOneCommentFromOneOwner(commentOwner, comment, userRequesting) {
delete comment.commenterId
delete comment.__v
return new Promise((resolve, reject) => {
Promise.all([
Upvote.countDocuments({postId: {$eq: comment._id}, postFormat: "Comment"}),
Downvote.countDocuments({postId: {$eq: comment._id}, postFormat: "Comment"}),
Upvote.findOne({postId: {$eq: comment._id}, postFormat: "Comment", userPublicId: userRequesting.secondId}),
Downvote.findOne({postId: {$eq: comment._id}, postFormat: "Comment", userPublicId: userRequesting.secondId})
]).then(([upvotes, downvotes, isUpvoted, isDownvoted]) => {
const commentObject = {
...comment,
votes: upvotes - downvotes,
commenterName: commentOwner.name,
commenterDisplayName: commentOwner.displayName,
profileImageKey: commentOwner.profileImageKey,
upvoted: !!isUpvoted,
downvoted: !!isDownvoted,
isOwner: commentOwner._id.toString() === userRequesting._id.toString(),
interacted: !!isUpvoted || !!isDownvoted,
_id: String(comment._id),
commenterId: String(comment.commenterId)
}

if (isUpvoted) {
commentObject.voteId = isUpvoted._id.toString()
}

if (isDownvoted) {
commentObject.voteId = isDownvoted._id.toString()
}

if (comment.parentCommentId) {
commentObject.parentCommentId = String(commentObject.parentCommentId)
}

resolve(commentObject)
}).catch(error => {
reject(`An error occured while executing Promise.all in CommentLibrary.processMultipleCommentsFromOneOwner: ${error}`)
})
})
}

processMultipleCommentsFromOneOwner(commentOwner, comments, userRequesting) {
return new Promise((resolve, reject) => {

Promise.all(
comments.map(comment => this.processOneCommentFromOneOwner(commentOwner, comment, userRequesting))
).then(images => {
resolve(images)
}).catch(error => {
reject(`An error occured in the final Promise.all in CommentLibrary.processMultipleCommentsFromOneOwner: ${error}`)
})
})
}
}

module.exports = CommentLibrary;
6 changes: 4 additions & 2 deletions libraries/ImagePost.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const Upvote = require('../models/Upvote')
const Downvote = require('../models/Downvote')
const ImagePost = require('../models/ImagePost')
const Comment = require('../models/Comment')
const ImageLibrary = require('../libraries/Image')
const imageLib = new ImageLibrary()

Expand All @@ -17,7 +18,8 @@ class ImagePostClass {
Downvote.countDocuments({postId: {$eq: post._id}, postFormat: "Image"}),
Upvote.findOne({postId: {$eq: post._id}, postFormat: "Image", userPublicId: userRequesting.secondId}),
Downvote.findOne({postId: {$eq: post._id}, postFormat: "Image", userPublicId: userRequesting.secondId}),
]).then(([upvotes, downvotes, isUpvoted, isDownvoted]) => {
Comment.countDocuments({postId: {$eq: post._id}, postFormat: "Image"})
]).then(([upvotes, downvotes, isUpvoted, isDownvoted, comments]) => {
const postObject = {
...post,
votes: upvotes - downvotes,
Expand All @@ -29,7 +31,7 @@ class ImagePostClass {
isOwner: postOwner._id.toString() === userRequesting._id.toString(),
interacted: !!isUpvoted || !!isDownvoted,
_id: post._id.toString(),
comments: Array.isArray(post.comments) ? post.comments.length : 0
comments
}

if (isUpvoted) {
Expand Down
8 changes: 5 additions & 3 deletions libraries/PollPost.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const Upvote = require('../models/Upvote')
const Downvote = require('../models/Downvote')
const Poll = require('../models/Poll')
const PollVote = require('../models/PollVote')
const Comment = require('../models/Comment')

class PollPost {
processMultiplePostDataFromOneOwner(posts, postOwner, userRequesting) {
Expand All @@ -22,8 +23,9 @@ class PollPost {
PollVote.countDocuments({pollId: {$eq: post._id}, vote: 'Three'}),
PollVote.countDocuments({pollId: {$eq: post._id}, vote: 'Four'}),
PollVote.countDocuments({pollId: {$eq: post._id}, vote: 'Five'}),
PollVote.countDocuments({pollId: {$eq: post._id}, vote: 'Six'})
]).then(([upvotes, downvotes, isUpvoted, isDownvoted, pollVote, optionOnesVotes, optionTwosVotes, optionThreesVotes, optionFoursVotes, optionFivesVotes, optionSixesVotes]) => {
PollVote.countDocuments({pollId: {$eq: post._id}, vote: 'Six'}),
Comment.countDocuments({postId: {$eq: post._id}, postFormat: "Poll"})
]).then(([upvotes, downvotes, isUpvoted, isDownvoted, pollVote, optionOnesVotes, optionTwosVotes, optionThreesVotes, optionFoursVotes, optionFivesVotes, optionSixesVotes, comments]) => {
const postObject = {
...post,
optionOnesVotes,
Expand All @@ -42,7 +44,7 @@ class PollPost {
isOwner: postOwner._id.toString() === userRequesting._id.toString(),
interacted: !!isUpvoted || !!isDownvoted,
votedFor: pollVote?.vote || "None",
comments: Array.isArray(post.comments) ? post.comments.length : 0
comments
}

if (isUpvoted) {
Expand Down
8 changes: 5 additions & 3 deletions libraries/ThreadPost.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const Downvote = require('../models/Downvote')
const Thread = require('../models/Thread')
const ImageLibrary = require('./Image')
const Category = require('../models/Category')
const Comment = require('../models/Comment')
const imageLib = new ImageLibrary()

class ThreadPost {
Expand All @@ -18,8 +19,9 @@ class ThreadPost {
Downvote.countDocuments({postId: {$eq: post._id}, postFormat: "Thread"}),
Upvote.findOne({postId: {$eq: post._id}, postFormat: "Thread", userPublicId: {$eq: userRequesting.secondId}}),
Downvote.findOne({postId: {$eq: post._id}, postFormat: "Thread", userPublicId: {$eq: userRequesting.secondId}}),
Category.findOne({_id: {$eq: post.threadCategoryId}}, {categoryTitle: 1})
]).then(([upvotes, downvotes, isUpvoted, isDownvoted, category]) => {
Category.findOne({_id: {$eq: post.threadCategoryId}}, {categoryTitle: 1}),
Comment.countDocuments({postId: {$eq: post._id}, postFormat: "Thread"})
]).then(([upvotes, downvotes, isUpvoted, isDownvoted, category, comments]) => {
const postObject = {
...post,
votes: upvotes - downvotes,
Expand All @@ -32,7 +34,7 @@ class ThreadPost {
interacted: !!isUpvoted || !!isDownvoted,
_id: String(post._id),
threadCategory: category.categoryTitle,
comments: Array.isArray(post.comments) ? post.comments.length : 0
comments
}

if (isUpvoted) {
Expand Down
4 changes: 3 additions & 1 deletion models/Comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ const CommentSchema = new Schema({
datePosted: Number,
parentCommentId: mongoose.Schema.Types.ObjectId,
postId: mongoose.Schema.Types.ObjectId,
postFormat: String
postFormat: String,
deleted: Boolean,
replies: {type: Number, default: 0}
});

const Comment = mongoose.model('Comment', CommentSchema);
Expand Down
Loading

0 comments on commit e8a6cbb

Please sign in to comment.