use fullfillPostsData

This commit is contained in:
srgooglo 2022-11-14 01:29:56 +00:00
parent 28ca8a633b
commit 1b19439b4d
2 changed files with 39 additions and 36 deletions

View File

@ -0,0 +1,34 @@
import { Post, UserFollow } from "../../../models"
import fullfillPostsData from "../../../utils/fullfillPostsData"
export default async (payload) => {
const {
for_user_id,
limit = 20,
skip = 0,
} = payload
// get post from users that the user follows
const followingUsers = await UserFollow.find({
user_id: for_user_id
})
const followingUserIds = followingUsers.map((followingUser) => followingUser.to)
let posts = await Post.find({
user_id: { $in: followingUserIds }
})
.sort({ created_at: -1 })
.limit(limit)
.skip(skip)
// fullfill data
posts = await fullfillPostsData({
posts,
for_user_id,
skip,
})
return posts
}

View File

@ -1,4 +1,5 @@
import { Post, User, Comment, SavedPost } from "../../../models"
import fullfillPostsData from "../../../utils/fullfillPostsData"
export default async (payload) => {
let {
@ -55,44 +56,12 @@ export default async (payload) => {
}
// fullfill data
posts = posts.map(async (post, index) => {
post = post.toObject()
post.key = Number(skip) + Number(index)
let user = await User.findById(post.user_id).catch(() => false)
if (!user) {
user = {
username: "Deleted user",
}
}
let comments = await Comment.find({ parent_id: post._id.toString() })
.select("_id")
.catch(() => false)
if (!comments) {
comments = []
}
post.comments = comments
if (for_user_id) {
post.isLiked = post.likes.includes(for_user_id)
post.isSaved = savedPostsIds.includes(post._id.toString())
}
return {
key: Number(skip) + Number(index),
...post,
comments: comments.map((comment) => comment._id.toString()),
user,
}
posts = await fullfillPostsData({
posts,
for_user_id,
skip,
})
posts = await Promise.all(posts)
// if post_id is specified, return only one post
if (post_id) {
return posts[0]