Files
juwan-frontend/lib/api/comments.ts
T

57 lines
1.5 KiB
TypeScript

import { addNotification } from "@/lib/api/notifications"
import { allow, deny } from "@/lib/decision"
import { useAuthStore } from "@/store/auth"
import { useCommentStore } from "@/store/comments"
import { usePostStore } from "@/store/posts"
export function listComments() {
return useCommentStore.getState().comments
}
export function listCommentsByPost(postId: string) {
return useCommentStore.getState().comments.filter((comment) => comment.postId === postId)
}
export function addComment(postId: string, content: string) {
const user = useAuthStore.getState().user
if (!user) {
return deny(401, "请先登录")
}
const post = usePostStore.getState().posts.find((item) => item.id === postId)
if (!post) {
return deny(404, "帖子不存在")
}
const comment = useCommentStore.getState().addComment(postId, user, content)
if (!comment) {
return deny(400, "评论内容不能为空")
}
usePostStore.getState().incrementCommentCount(postId)
addNotification({
type: "community",
title: "帖子收到新评论",
content: `${post.title}》有新的评论`,
link: `/post/${post.id}`,
})
return allow()
}
export function toggleCommentLike(commentId: string) {
const user = useAuthStore.getState().user
if (!user) {
return deny(401, "请先登录")
}
const comment = useCommentStore.getState().comments.find((item) => item.id === commentId)
if (!comment) {
return deny(404, "评论不存在")
}
useCommentStore.getState().toggleCommentLike(commentId)
return allow()
}