move like logic

This commit is contained in:
SrGooglo 2023-02-24 14:43:23 +00:00
parent 9c8cf720fd
commit 67c2464503
3 changed files with 37 additions and 20 deletions

View File

@ -1,31 +1,37 @@
import { Post } from "../../../models"
import modifyPostData from "./modifyPostData"
import { PostLike } from "@models"
export default async (payload) => {
let { post_id, user_id, to } = payload
let post = await Post.findById(post_id).catch(() => false)
if (!post) {
throw new Error("Post not found")
}
let likeObj = await PostLike.findOne({
post_id,
user_id,
}).catch(() => false)
if (typeof to === "undefined") {
to = !post.likes.includes(user_id)
if (likeObj) {
to = false
} else {
to = true
}
}
if (to) {
post.likes.push(user_id)
likeObj = new PostLike({
post_id,
user_id,
})
await likeObj.save()
} else {
post.likes = post.likes.filter((id) => id !== user_id)
await PostLike.findByIdAndDelete(likeObj._id)
}
post = await modifyPostData(post._id, { likes: post.likes })
global.websocket_instance.io.emit(`post.${post_id}.likes.update`, {
to,
post_id,
user_id,
})
global.websocket_instance.io.emit(`post.${to ? "like" : "unlike"}`, post)
global.websocket_instance.io.emit(`post.${to ? "like" : "unlike"}.${post.user_id}`, post)
global.websocket_instance.io.emit(`post.${to ? "like" : "unlike"}.${post_id}`, post)
return post
return likeObj
}

View File

@ -6,10 +6,7 @@ export default {
timestamp: { type: String, required: true },
created_at: { type: Date, default: Date.now, required: true },
message: { type: String },
likes: { type: Array, default: [] },
attachments: { type: Array, default: [] },
type: { type: String, default: "text" },
data: { type: Object, default: {} },
flags: { type: Array, default: [] },
}
}

View File

@ -0,0 +1,14 @@
export default {
name: "PostLike",
collection: "post_likes",
schema: {
user_id: {
type: String,
required: true,
},
post_id: {
type: String,
required: true,
}
}
}