diff --git a/app/api/posts/route.js b/app/api/posts/route.js
index 21cda61..f017e8e 100644
--- a/app/api/posts/route.js
+++ b/app/api/posts/route.js
@@ -1,4 +1,4 @@
-// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= 筛选
+// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= & 分页
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
@@ -6,9 +6,22 @@ export async function GET(req) {
const url = new URL(req.url);
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
const userId = url.searchParams.get('user_id');
+ const page = parseInt(url.searchParams.get('page')) || 1;
+ const limit = parseInt(url.searchParams.get('limit')) || 20;
+ const offset = (page - 1) * limit;
try {
- let query = `
+ const params = [];
+ let where = '';
+ if (userId) {
+ where = ' WHERE p.user_id = $1';
+ params.push(userId);
+ }
+
+ const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
+ const total = parseInt(countResult.rows[0]?.total || 0);
+
+ const r = await pool.query(`
SELECT
p.*,
u.username,
@@ -16,15 +29,15 @@ export async function GET(req) {
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
FROM posts p
JOIN users u ON p.user_id = u.id
- `;
- const params = [];
- if (userId) {
- query += ' WHERE p.user_id = $1';
- params.push(userId);
- }
- query += ` ORDER BY ${sort} DESC`;
- const r = await pool.query(query, params);
- return Response.json(r.rows);
+ ${where}
+ ORDER BY ${sort} DESC
+ LIMIT $${params.length + 1} OFFSET $${params.length + 2}
+ `, [...params, limit, offset]);
+
+ return Response.json({
+ data: r.rows,
+ pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
+ });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
diff --git a/components/Feed.js b/components/Feed.js
index c97c503..a6741d6 100644
--- a/components/Feed.js
+++ b/components/Feed.js
@@ -15,26 +15,34 @@ export default function Feed({ onOpenModal, onReport }) {
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
const [posts, setPosts] = useState(null);
const [error, setError] = useState(null);
+ const [page, setPage] = useState(1);
+ const [totalPages, setTotalPages] = useState(1);
+ const PAGE_SIZE = 20;
- const load = useCallback(async () => {
+ const load = useCallback(async (targetPage) => {
setPosts(null);
setError(null);
try {
- const data = await API.getPosts(sort);
- setPosts(data || []);
+ const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
+ setPosts(result.data || []);
+ setTotalPages(result.pagination?.totalPages || 1);
+ setPage(result.pagination?.page || 1);
} catch (err) {
setError(err.message);
setPosts([]);
}
}, [sort, refreshKey]);
- useEffect(() => { load(); }, [load]);
+ useEffect(() => { load(page); }, [load]);
+
+ // 排序切换时回第一页
+ useEffect(() => { setPage(1); }, [sort]);
const handleDelete = async (postId) => {
if (!confirm('确定要删除这条帖子吗?')) return;
try {
await API.deletePost(postId);
- load();
+ load(page);
} catch (err) {
alert('删除失败:' + err.message);
}
@@ -113,6 +121,43 @@ export default function Feed({ onOpenModal, onReport }) {
})
)}
+ {totalPages > 1 && posts && posts.length > 0 && (
+
+
+ {Array.from({ length: totalPages }, (_, i) => i + 1).map((i) => (
+
+ ))}
+
+
+ )}
);
}
diff --git a/components/NewPost.js b/components/NewPost.js
index ba0717a..902d48e 100644
--- a/components/NewPost.js
+++ b/components/NewPost.js
@@ -1,7 +1,7 @@
'use client';
// 发布新帖页
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useRef } from 'react';
import { API, generateCaptcha, uploadImage } from '@/lib/api';
import { useApp } from './AppProvider';
import { Icon } from './Icons';
@@ -23,13 +23,17 @@ export default function NewPost() {
try {
const newPreviews = [];
for (const file of files) {
+ if (!file.type.startsWith('image/')) continue;
+ if (file.size > 5 * 1024 * 1024) {
+ alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
+ continue;
+ }
const dataUrl = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.readAsDataURL(file);
});
newPreviews.push(dataUrl);
- // 直接上传拿 URL
const url = await uploadImage(file);
setImages((prev) => [...prev, url]);
}
@@ -41,6 +45,16 @@ export default function NewPost() {
}
};
+ // 拖拽上传
+ const [dragOver, setDragOver] = useState(false);
+ const fileInputRef = useRef(null);
+ const dropZoneStyle = {
+ border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'),
+ borderRadius: 8, padding: 24, textAlign: 'center', cursor: 'pointer',
+ transition: 'all 0.3s', margin: '8px 0 12px',
+ background: dragOver ? 'var(--primary-bg)' : 'var(--bg)',
+ };
+
const handleSubmit = async () => {
if (!currentUser || !currentUser.id) {
alert('请先登录');
@@ -87,16 +101,29 @@ export default function NewPost() {
/>
{previews.map((src, i) => (
-

+

))}
+ fileInputRef.current?.click()}
+ onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
+ onDragLeave={(e) => { e.preventDefault(); setDragOver(false); }}
+ onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files) handleFiles(Array.from(e.dataTransfer.files)); }}
+ >
+
+ {uploading ? '上传中...' : (dragOver ? '松开上传' : '📷 点击或拖拽上传图片')}
+
+
{ if (e.target.files) handleFiles(Array.from(e.target.files)); }}
- style={{ margin: '8px 0 12px' }}
/>
setCaptcha(generateCaptcha())} style={{ cursor: 'pointer' }}>
diff --git a/components/UserProfile.js b/components/UserProfile.js
index 9ac8c7d..67fb7e5 100644
--- a/components/UserProfile.js
+++ b/components/UserProfile.js
@@ -29,8 +29,8 @@ export default function UserProfile({ username }) {
return;
}
setUser(u);
- const userPosts = await API.getPosts('latest', u.id);
- setPosts(userPosts || []);
+ const result = await API.getPosts('latest', u.id);
+ setPosts(result.data || []);
} catch (err) {
setError(err.message || '加载失败');
}
diff --git a/lib/api.js b/lib/api.js
index 8bf8952..231ab5e 100644
--- a/lib/api.js
+++ b/lib/api.js
@@ -48,8 +48,8 @@ export const API = {
getMe() { return apiFetch('/auth/me'); },
// 帖子
- getPosts(sort, userId) {
- let q = '/posts?sort=' + (sort || 'latest');
+ getPosts(sort, userId, page = 1, limit = 20) {
+ let q = '/posts?sort=' + (sort || 'latest') + '&page=' + page + '&limit=' + limit;
if (userId) q += '&user_id=' + userId;
return apiFetch(q);
},