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

44 lines
1.1 KiB
TypeScript

import { addNotification } from "@/lib/api/notifications"
import { allow, deny } from "@/lib/decision"
import { useAuthStore } from "@/store/auth"
import { usePostStore } from "@/store/posts"
export function listPosts() {
return usePostStore.getState().posts
}
export function getPostById(postId: string) {
return usePostStore.getState().posts.find((post) => post.id === postId)
}
export function listPostsByAuthor(userId: string) {
return usePostStore.getState().posts.filter((post) => post.author.id === userId)
}
export function togglePostLike(postId: 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 shouldNotify = !post.liked
usePostStore.getState().togglePostLike(postId)
if (shouldNotify) {
addNotification({
type: "community",
title: "帖子收到点赞",
content: `${post.title}》有新的点赞`,
link: `/post/${post.id}`,
})
}
return allow()
}