feat(posts): wire community pages to backend posts API

This commit is contained in:
zetaloop
2026-02-28 17:25:57 +08:00
parent bffd8b4968
commit e94a7e68ff
5 changed files with 204 additions and 127 deletions
+94 -81
View File
@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card" import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card"
import { listGames, listOrders, listPlayers, listPosts } from "@/lib/api" import { listGames, listOrders, listPlayers, listPosts } from "@/lib/api"
import { roleLabels } from "@/lib/constants" import { roleLabels } from "@/lib/constants"
import type { Game, Player } from "@/lib/types" import type { Game, Player, Post } from "@/lib/types"
import { ClipboardList, Heart, MessageCircle, PenSquare, Pin } from "lucide-react" import { ClipboardList, Heart, MessageCircle, PenSquare, Pin } from "lucide-react"
import Link from "next/link" import Link from "next/link"
import { useEffect, useState } from "react" import { useEffect, useState } from "react"
@@ -14,7 +14,8 @@ import { useEffect, useState } from "react"
export default function CommunityPage() { export default function CommunityPage() {
const [games, setGames] = useState<Game[]>([]) const [games, setGames] = useState<Game[]>([])
const [players, setPlayers] = useState<Player[]>([]) const [players, setPlayers] = useState<Player[]>([])
const posts = listPosts() const [posts, setPosts] = useState<Post[]>([])
const [postsLoading, setPostsLoading] = useState(true)
const orders = listOrders() const orders = listOrders()
const [sortMode, setSortMode] = useState<"latest" | "hot">("latest") const [sortMode, setSortMode] = useState<"latest" | "hot">("latest")
@@ -23,16 +24,22 @@ export default function CommunityPage() {
useEffect(() => { useEffect(() => {
let cancelled = false let cancelled = false
Promise.all([listGames(), listPlayers()]) setPostsLoading(true)
.then(([gamesItems, playersItems]) => {
Promise.all([listGames(), listPlayers(), listPosts()])
.then(([gamesItems, playersItems, postsItems]) => {
if (cancelled) return if (cancelled) return
setGames(gamesItems) setGames(gamesItems)
setPlayers(playersItems) setPlayers(playersItems)
setPosts(postsItems)
setPostsLoading(false)
}) })
.catch(() => { .catch(() => {
if (cancelled) return if (cancelled) return
setGames([]) setGames([])
setPlayers([]) setPlayers([])
setPosts([])
setPostsLoading(false)
}) })
return () => { return () => {
@@ -98,86 +105,92 @@ export default function CommunityPage() {
</div> </div>
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
{filteredPosts.map((post) => {postsLoading ? (
(() => { <div className="text-center py-12 text-muted-foreground">...</div>
const linkedOrder = post.linkedOrderId ) : filteredPosts.length === 0 ? (
? orders.find((order) => order.id === post.linkedOrderId) <div className="text-center py-12 text-muted-foreground"></div>
: null ) : (
const linkedPlayer = linkedOrder filteredPosts.map((post) =>
? players.find((player) => player.id === linkedOrder.playerId) (() => {
: null const linkedOrder = post.linkedOrderId
? orders.find((order) => order.id === post.linkedOrderId)
: null
const linkedPlayer = linkedOrder
? players.find((player) => player.id === linkedOrder.playerId)
: null
return ( return (
<Link key={post.id} href={`/post/${post.id}`} className="block"> <Link key={post.id} href={`/post/${post.id}`} className="block">
<Card className="hover:shadow-md transition-shadow gap-4"> <Card className="hover:shadow-md transition-shadow gap-4">
<CardHeader> <CardHeader>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Avatar className="h-9 w-9"> <Avatar className="h-9 w-9">
<AvatarImage src={post.author.avatar} /> <AvatarImage src={post.author.avatar} />
<AvatarFallback>{post.author.nickname[0]}</AvatarFallback> <AvatarFallback>{post.author.nickname[0]}</AvatarFallback>
</Avatar> </Avatar>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-sm font-medium">{post.author.nickname}</span> <span className="text-sm font-medium">{post.author.nickname}</span>
<Badge variant="outline" className="text-[10px] px-1.5 py-0"> <Badge variant="outline" className="text-[10px] px-1.5 py-0">
{roleLabels[post.authorRole]} {roleLabels[post.authorRole]}
</Badge> </Badge>
{post.pinned && <Pin className="h-3 w-3 text-muted-foreground" />} {post.pinned && <Pin className="h-3 w-3 text-muted-foreground" />}
</div>
<span className="text-xs text-muted-foreground">
{new Date(post.createdAt).toLocaleDateString("zh-CN")}
</span>
</div>
</div>
</CardHeader>
<CardContent>
<h3 className="font-semibold mb-1">{post.title}</h3>
<p className="text-sm text-muted-foreground line-clamp-2">{post.content}</p>
{post.tags.length > 0 && (
<div className="flex flex-wrap gap-1 mt-2">
{post.tags.map((tag) => (
<Badge key={tag} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
</div>
)}
{post.linkedOrderId && (
<div className="mt-2 rounded-lg border bg-muted/30 px-3 py-2 text-xs text-muted-foreground space-y-1.5">
<div className="flex items-center gap-1.5">
<ClipboardList className="h-3.5 w-3.5" />
</div>
{linkedOrder && (
<div className="pl-5">
<p>
{linkedOrder.service.gameName} · {linkedOrder.service.title}
</p>
<p>
{linkedOrder.playerName}
{linkedPlayer ? ` · ${linkedPlayer.rating}` : ""}
</p>
</div> </div>
)} <span className="text-xs text-muted-foreground">
{new Date(post.createdAt).toLocaleDateString("zh-CN")}
</span>
</div>
</div> </div>
)} </CardHeader>
</CardContent> <CardContent>
<CardFooter className="text-sm text-muted-foreground gap-4"> <h3 className="font-semibold mb-1">{post.title}</h3>
<span className="flex items-center gap-1"> <p className="text-sm text-muted-foreground line-clamp-2">{post.content}</p>
<Heart {post.tags.length > 0 && (
className={`h-4 w-4 ${post.liked ? "fill-red-500 text-red-500" : ""}`} <div className="flex flex-wrap gap-1 mt-2">
/> {post.tags.map((tag) => (
{post.likeCount} <Badge key={tag} variant="secondary" className="text-xs">
</span> {tag}
<span className="flex items-center gap-1"> </Badge>
<MessageCircle className="h-4 w-4" /> ))}
{post.commentCount} </div>
</span> )}
</CardFooter> {post.linkedOrderId && (
</Card> <div className="mt-2 rounded-lg border bg-muted/30 px-3 py-2 text-xs text-muted-foreground space-y-1.5">
</Link> <div className="flex items-center gap-1.5">
) <ClipboardList className="h-3.5 w-3.5" />
})(),
</div>
{linkedOrder && (
<div className="pl-5">
<p>
{linkedOrder.service.gameName} · {linkedOrder.service.title}
</p>
<p>
{linkedOrder.playerName}
{linkedPlayer ? ` · ${linkedPlayer.rating}` : ""}
</p>
</div>
)}
</div>
)}
</CardContent>
<CardFooter className="text-sm text-muted-foreground gap-4">
<span className="flex items-center gap-1">
<Heart
className={`h-4 w-4 ${post.liked ? "fill-red-500 text-red-500" : ""}`}
/>
{post.likeCount}
</span>
<span className="flex items-center gap-1">
<MessageCircle className="h-4 w-4" />
{post.commentCount}
</span>
</CardFooter>
</Card>
</Link>
)
})(),
)
)} )}
</div> </div>
</div> </div>
+6 -2
View File
@@ -14,7 +14,7 @@ import { notFound } from "next/navigation"
export default async function PostDetailPage({ params }: { params: Promise<{ id: string }> }) { export default async function PostDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params const { id } = await params
const post = getPostById(id) const post = await getPostById(id)
if (!post) notFound() if (!post) notFound()
const linkedOrder = post.linkedOrderId ? getOrderById(post.linkedOrderId) : null const linkedOrder = post.linkedOrderId ? getOrderById(post.linkedOrderId) : null
@@ -91,7 +91,11 @@ export default async function PostDetailPage({ params }: { params: Promise<{ id:
)} )}
<div className="flex items-center gap-4 text-sm text-muted-foreground pt-2"> <div className="flex items-center gap-4 text-sm text-muted-foreground pt-2">
<PostLikeButton postId={post.id} /> <PostLikeButton
postId={post.id}
initialLiked={post.liked}
initialLikeCount={post.likeCount}
/>
<PostCommentCount postId={post.id} /> <PostCommentCount postId={post.id} />
</div> </div>
</CardContent> </CardContent>
+1 -1
View File
@@ -22,7 +22,7 @@ export default async function UserProfilePage({ params }: { params: Promise<{ id
} }
const [userPosts, userFavorites, players, shops] = await Promise.all([ const [userPosts, userFavorites, players, shops] = await Promise.all([
listPostsByAuthor(user.id), listPostsByAuthor(id),
listFavoritesByUser(user.id), listFavoritesByUser(user.id),
listPlayers(), listPlayers(),
listShops(), listShops(),
+36 -11
View File
@@ -1,34 +1,59 @@
"use client" "use client"
import { togglePostLike } from "@/lib/api/posts" import { togglePostLike } from "@/lib/api/posts"
import { toApiError } from "@/lib/errors"
import { notifyInfo } from "@/lib/toast"
import { useRequireAuth } from "@/lib/use-require-auth" import { useRequireAuth } from "@/lib/use-require-auth"
import { usePostStore } from "@/store/posts"
import { Heart } from "lucide-react" import { Heart } from "lucide-react"
import { useState } from "react"
interface PostLikeButtonProps { interface PostLikeButtonProps {
postId: string postId: string
initialLiked: boolean
initialLikeCount: number
} }
export function PostLikeButton({ postId }: PostLikeButtonProps) { export function PostLikeButton({ postId, initialLiked, initialLikeCount }: PostLikeButtonProps) {
const { requireAuth } = useRequireAuth() const { requireAuth } = useRequireAuth()
const post = usePostStore((state) => state.posts.find((item) => item.id === postId)) const [liked, setLiked] = useState(initialLiked)
const [likeCount, setLikeCount] = useState(initialLikeCount)
if (!post) { const [pending, setPending] = useState(false)
return null
}
return ( return (
<button <button
type="button" type="button"
className="flex items-center gap-1 hover:text-foreground transition-colors" disabled={pending}
className="flex items-center gap-1 hover:text-foreground transition-colors disabled:opacity-60 disabled:pointer-events-none"
onClick={() => onClick={() =>
requireAuth(() => { requireAuth(() => {
togglePostLike(postId) if (pending) return
const prevLiked = liked
const prevCount = likeCount
const nextLiked = !prevLiked
setLiked(nextLiked)
setLikeCount(Math.max(0, prevCount + (nextLiked ? 1 : -1)))
setPending(true)
togglePostLike(postId, prevLiked)
.catch((err: unknown) => {
setLiked(prevLiked)
setLikeCount(prevCount)
if (err instanceof Error && err.message === "UNAUTHORIZED") {
notifyInfo("请先登录")
return
}
notifyInfo(toApiError(err).msg)
})
.finally(() => {
setPending(false)
})
}) })
} }
> >
<Heart className={`h-4 w-4 ${post.liked ? "fill-red-500 text-red-500" : ""}`} /> <Heart className={`h-4 w-4 ${liked ? "fill-red-500 text-red-500" : ""}`} />
{post.likeCount} {likeCount}
</button> </button>
) )
} }
+67 -32
View File
@@ -1,43 +1,78 @@
import { addNotification } from "@/lib/api/notifications" import { isApiError } from "@/lib/errors"
import { allow, deny } from "@/lib/decision" import type { Post } from "@/lib/types"
import { useAuthStore } from "@/store/auth"
import { usePostStore } from "@/store/posts"
export function listPosts() { import { httpJson } from "./http"
return usePostStore.getState().posts
}
export function getPostById(postId: string) { type Paginated<T> = {
return usePostStore.getState().posts.find((post) => post.id === postId) items: T[]
} meta: {
total: number
export function listPostsByAuthor(userId: string) { offset: number
return usePostStore.getState().posts.filter((post) => post.author.id === userId) limit: number
}
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) type ListOptions = {
if (!post) { offset?: number
return deny(404, "帖子不存在") limit?: number
} }
const shouldNotify = !post.liked function withOffsetLimit(path: string, options?: ListOptions): string {
const offset = options?.offset ?? 0
const limit = options?.limit ?? 1000
usePostStore.getState().togglePostLike(postId) const searchParams = new URLSearchParams({
offset: String(offset),
limit: String(limit),
})
return `${path}?${searchParams.toString()}`
}
if (shouldNotify) { export async function listPosts(options?: ListOptions): Promise<Post[]> {
addNotification({ const res = await httpJson<Paginated<Post>>(withOffsetLimit("/api/v1/posts", options), {
type: "community", cache: "no-store",
title: "帖子收到点赞", })
content: `${post.title}》有新的点赞`, return res.items
link: `/post/${post.id}`, }
export async function getPostById(postId: string): Promise<Post | undefined> {
try {
return await httpJson<Post>(`/api/v1/posts/${encodeURIComponent(postId)}`, {
cache: "no-store",
}) })
} catch (error) {
if (error instanceof Error && error.message === "UNAUTHORIZED") {
throw error
}
if (isApiError(error) && error.code === 404) {
return undefined
}
throw error
}
}
export async function listPostsByAuthor(userId: string, options?: ListOptions): Promise<Post[]> {
const res = await httpJson<Paginated<Post>>(
withOffsetLimit(`/api/v1/users/${encodeURIComponent(userId)}/posts`, options),
{
cache: "no-store",
},
)
return res.items
}
export async function togglePostLike(postId: string, currentlyLiked: boolean): Promise<void> {
const encodedId = encodeURIComponent(postId)
if (currentlyLiked) {
await httpJson<unknown>(`/api/v1/posts/${encodedId}/like`, {
method: "DELETE",
cache: "no-store",
})
return
} }
return allow() await httpJson<unknown>(`/api/v1/posts/${encodedId}/like`, {
method: "POST",
cache: "no-store",
})
} }