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 { PostLike } from "@models"
import modifyPostData from "./modifyPostData"
export default async (payload) => { export default async (payload) => {
let { post_id, user_id, to } = payload let { post_id, user_id, to } = payload
let post = await Post.findById(post_id).catch(() => false) let likeObj = await PostLike.findOne({
post_id,
if (!post) { user_id,
throw new Error("Post not found") }).catch(() => false)
}
if (typeof to === "undefined") { if (typeof to === "undefined") {
to = !post.likes.includes(user_id) if (likeObj) {
to = false
} else {
to = true
}
} }
if (to) { if (to) {
post.likes.push(user_id) likeObj = new PostLike({
post_id,
user_id,
})
await likeObj.save()
} else { } 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) return likeObj
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
} }

View File

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