fix: support replies on legacy databases
This commit is contained in:
1 parent
68b58851e8
commit
3840bb3c54
4 files changed
+145
-24
No files matched your search
@@ -4,22 +4,49 @@ import { getUser } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
|
||||
|
||||
function repliesSelectSql(capabilities) {
|
||||
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,
|
||||
ru.username AS reply_to_username
|
||||
FROM replies r
|
||||
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
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
if (capabilities.replyToUsername) {
|
||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||
NULL::uuid AS reply_to_id,
|
||||
u.username, u.avatar_url,
|
||||
r.reply_to_username
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||
NULL::uuid AS reply_to_id,
|
||||
NULL::varchar AS reply_to_username,
|
||||
u.username, u.avatar_url
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`SELECT r.*, u.username, u.avatar_url,
|
||||
ru.username AS reply_to_username
|
||||
FROM replies r
|
||||
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
|
||||
ORDER BY r.created_at ASC`,
|
||||
[(await params).id]
|
||||
);
|
||||
const capabilities = await getReplySchemaCapabilities();
|
||||
const r = await pool.query(repliesSelectSql(capabilities), [(await params).id]);
|
||||
return jsonWithEtag(req, r.rows);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
console.error('[replies] list failed:', error?.code || error?.message);
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -29,7 +56,7 @@ export async function POST(req, { params }) {
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { content, captcha_id, captcha_answer, captcha_sig, reply_to_id } = await req.json();
|
||||
const { content, captcha_id, captcha_answer, captcha_sig, reply_to_id, reply_to_username } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写回复内容' }, { status: 400 });
|
||||
}
|
||||
@@ -38,16 +65,65 @@ export async function POST(req, { params }) {
|
||||
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content, reply_to_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING *`,
|
||||
[(await params).id, user.id, content, reply_to_id || null]
|
||||
);
|
||||
const postId = (await params).id;
|
||||
const capabilities = await getReplySchemaCapabilities();
|
||||
let replyTargetUsername = null;
|
||||
|
||||
if (reply_to_id) {
|
||||
const target = await pool.query(
|
||||
`SELECT u.username
|
||||
FROM replies r
|
||||
JOIN users u ON u.id = r.user_id
|
||||
WHERE r.id = $1 AND r.post_id = $2`,
|
||||
[reply_to_id, postId]
|
||||
);
|
||||
if (!target.rows[0]) {
|
||||
return Response.json({ error: '回复目标不存在' }, { status: 400 });
|
||||
}
|
||||
replyTargetUsername = target.rows[0].username;
|
||||
} else if (reply_to_username && capabilities.replyToUsername) {
|
||||
const target = await pool.query(
|
||||
`SELECT u.username
|
||||
FROM replies r
|
||||
JOIN users u ON u.id = r.user_id
|
||||
WHERE r.post_id = $1 AND u.username = $2
|
||||
LIMIT 1`,
|
||||
[postId, reply_to_username]
|
||||
);
|
||||
if (!target.rows[0]) {
|
||||
return Response.json({ error: '回复目标不存在' }, { status: 400 });
|
||||
}
|
||||
replyTargetUsername = target.rows[0].username;
|
||||
}
|
||||
|
||||
let r;
|
||||
if (capabilities.replyToId) {
|
||||
r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content, reply_to_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING *`,
|
||||
[postId, user.id, content.trim(), reply_to_id || null]
|
||||
);
|
||||
} else if (capabilities.replyToUsername) {
|
||||
r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content, reply_to_username)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING *, NULL::uuid AS reply_to_id`,
|
||||
[postId, user.id, content.trim(), replyTargetUsername]
|
||||
);
|
||||
} else {
|
||||
r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *, NULL::uuid AS reply_to_id, NULL::varchar AS reply_to_username`,
|
||||
[postId, user.id, content.trim()]
|
||||
);
|
||||
}
|
||||
await logAudit(req, 'create_reply', user.id);
|
||||
await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [(await params).id]);
|
||||
await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [postId]);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
console.error('[replies] create failed:', error?.code || error?.message);
|
||||
return Response.json({ error: '回复失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,13 @@ export default function ReplyList({ postId, onRefresh }) {
|
||||
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'warning'); return; }
|
||||
try {
|
||||
// 答案由服务端 HMAC 校验
|
||||
await API.createReply(postId, content.trim(), { id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig }, replyTo);
|
||||
await API.createReply(
|
||||
postId,
|
||||
content.trim(),
|
||||
{ id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig },
|
||||
replyTo,
|
||||
replyToObj?.username
|
||||
);
|
||||
setContent('');
|
||||
setCaptchaInput('');
|
||||
setReplyTo(null);
|
||||
|
||||
+9
-2
@@ -77,10 +77,17 @@ export const API = {
|
||||
|
||||
// 回复
|
||||
getReplies(postId) { return apiFetch('/posts/' + postId + '/replies'); },
|
||||
createReply(postId, content, captcha, replyToId) {
|
||||
createReply(postId, content, captcha, replyToId, replyToUsername) {
|
||||
return apiFetch('/posts/' + postId + '/replies', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ content, captcha_id: captcha?.id, captcha_answer: captcha?.answer, captcha_sig: captcha?.sig, reply_to_id: replyToId || null }),
|
||||
body: JSON.stringify({
|
||||
content,
|
||||
captcha_id: captcha?.id,
|
||||
captcha_answer: captcha?.answer,
|
||||
captcha_sig: captcha?.sig,
|
||||
reply_to_id: replyToId || null,
|
||||
reply_to_username: replyToUsername || null,
|
||||
}),
|
||||
});
|
||||
},
|
||||
deleteReply(replyId) { return apiFetch('/replies/' + replyId, { method: 'DELETE' }); },
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// 回复表兼容层:存量数据库不会因 CREATE TABLE IF NOT EXISTS 自动获得新列。
|
||||
// 仅读取现有结构,不在用户请求中执行 DDL;旧库降级到
|
||||
// reply_to_username 或不记录回复目标,避免读取和普通回复整体失败。
|
||||
import pool from '@/lib/db';
|
||||
|
||||
const REPLY_COLUMNS_SQL = `
|
||||
SELECT attname AS column_name
|
||||
FROM pg_attribute
|
||||
WHERE attrelid = to_regclass('replies')
|
||||
AND attnum > 0
|
||||
AND NOT attisdropped
|
||||
AND attname IN ('reply_to_id', 'reply_to_username')
|
||||
`;
|
||||
|
||||
async function inspectReplyColumns() {
|
||||
const result = await pool.query(REPLY_COLUMNS_SQL);
|
||||
const columns = new Set(result.rows.map((row) => row.column_name));
|
||||
return {
|
||||
replyToId: columns.has('reply_to_id'),
|
||||
replyToUsername: columns.has('reply_to_username'),
|
||||
};
|
||||
}
|
||||
|
||||
export function getReplySchemaCapabilities() {
|
||||
if (!globalThis.__forumlifyReplySchemaPromise) {
|
||||
globalThis.__forumlifyReplySchemaPromise = inspectReplyColumns().catch((error) => {
|
||||
globalThis.__forumlifyReplySchemaPromise = null;
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
return globalThis.__forumlifyReplySchemaPromise;
|
||||
}
|
||||
Reference in new issue
Block a user