fix: restore dark post view and API revalidation
This commit is contained in:
1 parent
773db0dec7
commit
b60aff7c25
12 files changed
+100
-31
No files matched your search
@@ -1,5 +1,6 @@
|
|||||||
// GET /api/custom-pages/[name] — 公开单个页面
|
// GET /api/custom-pages/[name] — 公开单个页面
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
export async function GET(req, { params }) {
|
export async function GET(req, { params }) {
|
||||||
try {
|
try {
|
||||||
@@ -10,7 +11,7 @@ export async function GET(req, { params }) {
|
|||||||
if (r.rows.length === 0) {
|
if (r.rows.length === 0) {
|
||||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||||
}
|
}
|
||||||
return Response.json(r.rows[0]);
|
return jsonWithEtag(req, r.rows[0]);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
// GET /api/custom-pages — 公开页面列表
|
// GET /api/custom-pages — 公开页面列表
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(req) {
|
||||||
try {
|
try {
|
||||||
const r = await pool.query(
|
const r = await pool.query(
|
||||||
'SELECT id, name, title FROM custom_pages WHERE enabled = true ORDER BY created_at'
|
'SELECT id, name, title FROM custom_pages WHERE enabled = true ORDER BY created_at'
|
||||||
);
|
);
|
||||||
return Response.json(r.rows);
|
return jsonWithEtag(req, r.rows);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
// GET /api/links, POST /api/links
|
// GET /api/links, POST /api/links
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser, requireAdmin } from '@/lib/auth';
|
import { getUser, requireAdmin } from '@/lib/auth';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||||
export const dynamic = 'force-dynamic';
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(req) {
|
||||||
try {
|
try {
|
||||||
const r = await pool.query('SELECT * FROM friendly_links ORDER BY sort_order');
|
const r = await pool.query('SELECT * FROM friendly_links ORDER BY sort_order');
|
||||||
return Response.json(r.rows);
|
return jsonWithEtag(req, r.rows);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// GET /api/posts/[id]/replies, POST /api/posts/[id]/replies
|
// GET /api/posts/[id]/replies, POST /api/posts/[id]/replies
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser } from '@/lib/auth';
|
import { getUser } from '@/lib/auth';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
export async function GET(req, { params }) {
|
export async function GET(req, { params }) {
|
||||||
try {
|
try {
|
||||||
@@ -12,7 +13,7 @@ export async function GET(req, { params }) {
|
|||||||
ORDER BY r.created_at ASC`,
|
ORDER BY r.created_at ASC`,
|
||||||
[(await params).id]
|
[(await params).id]
|
||||||
);
|
);
|
||||||
return Response.json(r.rows);
|
return jsonWithEtag(req, r.rows);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// GET /api/posts/[id], DELETE /api/posts/[id]
|
// GET /api/posts/[id], DELETE /api/posts/[id]
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser } from '@/lib/auth';
|
import { getUser } from '@/lib/auth';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
@@ -21,7 +22,7 @@ export async function GET(req, { params }) {
|
|||||||
if (r.rows.length === 0) {
|
if (r.rows.length === 0) {
|
||||||
return invalidId();
|
return invalidId();
|
||||||
}
|
}
|
||||||
return Response.json(r.rows[0]);
|
return jsonWithEtag(req, r.rows[0]);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= & 分页
|
// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= & 分页
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser } from '@/lib/auth';
|
import { getUser } from '@/lib/auth';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||||
export const dynamic = 'force-dynamic';
|
export const dynamic = 'force-dynamic';
|
||||||
@@ -38,7 +39,7 @@ export async function GET(req) {
|
|||||||
LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
|
LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
|
||||||
`, [...params, limit, offset]);
|
`, [...params, limit, offset]);
|
||||||
|
|
||||||
return Response.json({
|
return jsonWithEtag(req, {
|
||||||
data: r.rows,
|
data: r.rows,
|
||||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,23 +1,24 @@
|
|||||||
// GET /api/settings, PUT /api/settings
|
// GET /api/settings, PUT /api/settings
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
import { getUser, requireAdmin } from '@/lib/auth';
|
import { getUser, requireAdmin } from '@/lib/auth';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
// 避免 GET 被静态优化导致 PUT 405(动态接口,不能缓存)
|
// 避免 GET 被静态优化导致 PUT 405(动态接口,不能缓存)
|
||||||
export const dynamic = 'force-dynamic';
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(req) {
|
||||||
try {
|
try {
|
||||||
// 确保 forum_name 始终存在(未设置过则初始化默认值),前端拿到后显示
|
// 确保 forum_name 始终存在(未设置过则初始化默认值),前端拿到后显示
|
||||||
await pool.query(
|
await pool.query(
|
||||||
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||||
ON CONFLICT (key) DO NOTHING`
|
ON CONFLICT (key) DO NOTHING`
|
||||||
);
|
);
|
||||||
const r = await pool.query('SELECT key, value FROM settings');
|
const r = await pool.query('SELECT key, value FROM settings ORDER BY key');
|
||||||
const settings = {};
|
const settings = {};
|
||||||
r.rows.forEach((row) => { settings[row.key] = row.value; });
|
r.rows.forEach((row) => { settings[row.key] = row.value; });
|
||||||
// 兜底:即使插入失败也保证返回 forum_name
|
// 兜底:即使插入失败也保证返回 forum_name
|
||||||
if (!settings.forum_name) settings.forum_name = 'Forumlify';
|
if (!settings.forum_name) settings.forum_name = 'Forumlify';
|
||||||
return Response.json(settings);
|
return jsonWithEtag(req, settings);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
// GET /api/users/profile/:username — 用户公开信息(无需登录,用于用户主页)
|
// GET /api/users/profile/:username — 用户公开信息(无需登录,用于用户主页)
|
||||||
import pool from '@/lib/db';
|
import pool from '@/lib/db';
|
||||||
|
import { jsonWithEtag } from '@/lib/http-cache';
|
||||||
|
|
||||||
export async function GET(req, { params }) {
|
export async function GET(req, { params }) {
|
||||||
const { username } = await params;
|
const { username } = await params;
|
||||||
@@ -14,7 +15,7 @@ export async function GET(req, { params }) {
|
|||||||
if (r.rows.length === 0) {
|
if (r.rows.length === 0) {
|
||||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||||
}
|
}
|
||||||
return Response.json(r.rows[0]);
|
return jsonWithEtag(req, r.rows[0]);
|
||||||
} catch {
|
} catch {
|
||||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1438,7 +1438,7 @@ svg {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[data-theme="dark"] .page-slide {
|
[data-theme="dark"] .page-slide {
|
||||||
background: rgba(0, 0, 0, 0.3);
|
background: linear-gradient(145deg, var(--bg-start) 0%, var(--bg-end) 100%);
|
||||||
}
|
}
|
||||||
|
|
||||||
[data-theme="dark"] #replyArea textarea {
|
[data-theme="dark"] #replyArea textarea {
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
const REVALIDATE_CACHE_CONTROL = 'public, max-age=0, must-revalidate';
|
||||||
|
|
||||||
|
function matchesEtag(ifNoneMatch, etag) {
|
||||||
|
if (!ifNoneMatch) return false;
|
||||||
|
|
||||||
|
const normalized = etag.replace(/^W\//, '');
|
||||||
|
return ifNoneMatch.split(',').some((candidate) => {
|
||||||
|
const value = candidate.trim();
|
||||||
|
return value === '*' || value.replace(/^W\//, '') === normalized;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createEtag(body) {
|
||||||
|
const bytes = new TextEncoder().encode(body);
|
||||||
|
const digest = await crypto.subtle.digest('SHA-256', bytes);
|
||||||
|
const hash = Array.from(new Uint8Array(digest), (byte) =>
|
||||||
|
byte.toString(16).padStart(2, '0')
|
||||||
|
).join('');
|
||||||
|
return `"${hash}"`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function jsonWithEtag(req, data, init = {}) {
|
||||||
|
const body = JSON.stringify(data);
|
||||||
|
const etag = await createEtag(body);
|
||||||
|
const headers = new Headers(init.headers);
|
||||||
|
|
||||||
|
headers.set('Cache-Control', REVALIDATE_CACHE_CONTROL);
|
||||||
|
headers.set('ETag', etag);
|
||||||
|
|
||||||
|
if (matchesEtag(req.headers.get('if-none-match'), etag)) {
|
||||||
|
return new Response(null, { status: 304, headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
headers.set('Content-Type', 'application/json; charset=utf-8');
|
||||||
|
return new Response(body, { ...init, headers });
|
||||||
|
}
|
||||||
+2
-18
@@ -1,5 +1,7 @@
|
|||||||
/** @type {import('next').NextConfig} */
|
/** @type {import('next').NextConfig} */
|
||||||
const nextConfig = {
|
const nextConfig = {
|
||||||
|
// 本地开发同时支持 localhost 和 127.0.0.1,避免客户端脚本被跨源保护拦截。
|
||||||
|
allowedDevOrigins: ['127.0.0.1'],
|
||||||
// Docker 部署用 standalone 输出;serverless(Vercel/CF Pages)不需要
|
// Docker 部署用 standalone 输出;serverless(Vercel/CF Pages)不需要
|
||||||
...(process.env.DOCKER ? { output: 'standalone' } : {}),
|
...(process.env.DOCKER ? { output: 'standalone' } : {}),
|
||||||
// /uploads/* 由 API 路由提供(上传文件运行时新增,不进 public 构建快照)
|
// /uploads/* 由 API 路由提供(上传文件运行时新增,不进 public 构建快照)
|
||||||
@@ -8,24 +10,6 @@ const nextConfig = {
|
|||||||
{ source: '/uploads/:name', destination: '/api/uploads/:name' },
|
{ source: '/uploads/:name', destination: '/api/uploads/:name' },
|
||||||
];
|
];
|
||||||
},
|
},
|
||||||
// 缓存策略:动态页面/API no-cache(浏览器每次验证 → 304);
|
|
||||||
// 静态资源(_next/static)immutable 长缓存(Next.js 默认,但需在 no-cache 之后覆盖)
|
|
||||||
async headers() {
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
source: '/:path*',
|
|
||||||
headers: [
|
|
||||||
{ key: 'Cache-Control', value: 'no-cache, must-revalidate' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
source: '/_next/static/:path*',
|
|
||||||
headers: [
|
|
||||||
{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = nextConfig;
|
module.exports = nextConfig;
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { jsonWithEtag } from '../lib/http-cache.js';
|
||||||
|
|
||||||
|
test('jsonWithEtag returns a cacheable JSON response', async () => {
|
||||||
|
const req = new Request('https://example.test/api/posts');
|
||||||
|
const res = await jsonWithEtag(req, { data: ['post'] });
|
||||||
|
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
assert.equal(res.headers.get('cache-control'), 'public, max-age=0, must-revalidate');
|
||||||
|
assert.match(res.headers.get('etag'), /^"[0-9a-f]{64}"$/);
|
||||||
|
assert.deepEqual(await res.json(), { data: ['post'] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('jsonWithEtag returns 304 when the validator matches', async () => {
|
||||||
|
const initial = await jsonWithEtag(
|
||||||
|
new Request('https://example.test/api/posts'),
|
||||||
|
{ data: ['post'] }
|
||||||
|
);
|
||||||
|
const etag = initial.headers.get('etag');
|
||||||
|
const conditional = await jsonWithEtag(
|
||||||
|
new Request('https://example.test/api/posts', {
|
||||||
|
headers: { 'If-None-Match': `W/${etag}` },
|
||||||
|
}),
|
||||||
|
{ data: ['post'] }
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(conditional.status, 304);
|
||||||
|
assert.equal(conditional.headers.get('etag'), etag);
|
||||||
|
assert.equal(await conditional.text(), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('jsonWithEtag returns new content when the validator is stale', async () => {
|
||||||
|
const req = new Request('https://example.test/api/posts', {
|
||||||
|
headers: { 'If-None-Match': '"stale"' },
|
||||||
|
});
|
||||||
|
const res = await jsonWithEtag(req, { data: ['updated'] });
|
||||||
|
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
assert.deepEqual(await res.json(), { data: ['updated'] });
|
||||||
|
});
|
||||||
Reference in new issue
Block a user