feat: follow lite forum updates

This commit is contained in:
lezi-fun committed 2026-10-01 14:10:12 +08:00
1 parent f59739e36f
commit b42944b687
38 files changed
+1433 -71

No files matched your search

+14 -6
View File
@@ -6,8 +6,12 @@ import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
import { resolvePostReference } from '@/lib/post-reference';
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
function repliesSelectSql(capabilities) {
function repliesSelectSql(capabilities, viewer) {
const visible = viewer ? ` AND NOT EXISTS (
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = r.user_id
)` : '';
if (capabilities.replyToId) {
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
r.reply_to_id, u.username, u.avatar_url,
@@ -16,7 +20,7 @@ function repliesSelectSql(capabilities) {
JOIN users u ON r.user_id = u.id
LEFT JOIN replies rt ON r.reply_to_id = rt.id
LEFT JOIN users ru ON rt.user_id = ru.id
WHERE r.post_id = $1
WHERE r.post_id = $1${visible}
ORDER BY r.created_at ASC`;
}
@@ -27,7 +31,7 @@ function repliesSelectSql(capabilities) {
r.reply_to_username
FROM replies r
JOIN users u ON r.user_id = u.id
WHERE r.post_id = $1
WHERE r.post_id = $1${visible}
ORDER BY r.created_at ASC`;
}
@@ -37,7 +41,7 @@ function repliesSelectSql(capabilities) {
u.username, u.avatar_url
FROM replies r
JOIN users u ON r.user_id = u.id
WHERE r.post_id = $1
WHERE r.post_id = $1${visible}
ORDER BY r.created_at ASC`;
}
@@ -45,9 +49,13 @@ export async function GET(req, { params }) {
try {
const reference = await resolvePostReference((await params).id);
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
const viewer = getUser(req);
if (viewer) await ensureUserBlocksSchema();
const capabilities = await getReplySchemaCapabilities();
const r = await pool.query(repliesSelectSql(capabilities), [reference.id]);
return jsonWithEtag(req, r.rows);
const r = await pool.query(repliesSelectSql(capabilities, viewer), viewer ? [reference.id, viewer.id] : [reference.id]);
return viewer
? Response.json(r.rows, { headers: { 'Cache-Control': 'private, no-store' } })
: jsonWithEtag(req, r.rows);
} catch (error) {
console.error('[replies] list failed:', error?.code || error?.message);
return Response.json({ error: '服务器错误' }, { status: 500 });
+10 -3
View File
@@ -3,6 +3,7 @@ import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
import { resolvePostReference } from '@/lib/post-reference';
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
function invalidId() {
return Response.json({ error: '帖子不存在' }, { status: 404 });
@@ -10,19 +11,25 @@ function invalidId() {
export async function GET(req, { params }) {
try {
const viewer = getUser(req);
const reference = await resolvePostReference((await params).id);
if (!reference) return invalidId();
if (viewer) await ensureUserBlocksSchema();
const r = await pool.query(
`SELECT p.*, u.username, u.avatar_url, u.signature
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE p.id = $1`,
[reference.id]
WHERE p.id = $1${viewer ? ` AND NOT EXISTS (
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = p.user_id
)` : ''}`,
viewer ? [reference.id, viewer.id] : [reference.id]
);
if (r.rows.length === 0) {
return invalidId();
}
return jsonWithEtag(req, r.rows[0]);
return viewer
? Response.json(r.rows[0], { headers: { 'Cache-Control': 'private, no-store' } })
: jsonWithEtag(req, r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
+19 -6
View File
@@ -5,6 +5,7 @@ import { jsonWithEtag } from '@/lib/http-cache';
import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
import { ensurePostNumberSchema } from '@/lib/post-reference';
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
@@ -14,6 +15,7 @@ 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 viewer = getUser(req);
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
@@ -24,11 +26,19 @@ export async function GET(req) {
try {
await ensurePostNumberSchema();
const params = [];
let where = '';
const conditions = [];
if (userId) {
where = ' WHERE p.user_id = $1';
(await params).push(userId);
params.push(userId);
conditions.push(`p.user_id = $${params.length}`);
}
if (viewer) {
await ensureUserBlocksSchema();
params.push(viewer.id);
conditions.push(`NOT EXISTS (
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $${params.length} AND b.blocked_id = p.user_id
)`);
}
const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
const total = parseInt(countResult.rows[0]?.total || 0);
@@ -44,13 +54,16 @@ export async function GET(req) {
JOIN users u ON p.user_id = u.id
${where}
ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST, ${sort} DESC
LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
LIMIT $${params.length + 1} OFFSET $${params.length + 2}
`, [...params, limit, offset]);
return jsonWithEtag(req, {
const payload = {
data: r.rows,
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
});
};
return viewer
? Response.json(payload, { headers: { 'Cache-Control': 'private, no-store' } })
: jsonWithEtag(req, payload);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
+51
View File
@@ -0,0 +1,51 @@
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
import { ensurePostNumberSchema } from '@/lib/post-reference';
import { ensureUserBlocksSchema } from '@/lib/user-blocks';
export const dynamic = 'force-dynamic';
function escapeLike(value) {
return value.replace(/[\\%_]/g, (character) => `\\${character}`);
}
export async function GET(req) {
const url = new URL(req.url);
const keyword = (url.searchParams.get('q') || '').trim();
if (!keyword) return Response.json({ error: '请输入搜索关键词' }, { status: 400 });
if (keyword.length > 100) return Response.json({ error: '搜索关键词过长(最多 100 字)' }, { status: 400 });
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit'), 10) || 20));
const page = Math.min(10000, Math.max(1, parseInt(url.searchParams.get('page'), 10) || 1));
const user = getUser(req);
const values = [`%${escapeLike(keyword)}%`];
let where = '(p.title ILIKE $1 OR p.content ILIKE $1)';
try {
if (user) {
await ensureUserBlocksSchema();
values.push(user.id);
where += ` AND NOT EXISTS (
SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = p.user_id
)`;
}
await ensurePostNumberSchema();
const count = await pool.query(`SELECT COUNT(*) AS total FROM posts p WHERE ${where}`, values);
const total = Number(count.rows[0].total);
const rows = await pool.query(`
SELECT p.*, u.username, u.avatar_url, u.signature,
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) AS reply_count
FROM posts p JOIN users u ON u.id = p.user_id
WHERE ${where}
ORDER BY p.created_at DESC
LIMIT $${values.length + 1} OFFSET $${values.length + 2}
`, [...values, limit, (page - 1) * limit]);
return Response.json({
data: rows.rows,
query: keyword,
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
}, { headers: { 'Cache-Control': 'private, no-store' } });
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
}