diff --git a/app/api/custom-pages/[name]/route.js b/app/api/custom-pages/[name]/route.js index bf398d3..d64ec57 100644 --- a/app/api/custom-pages/[name]/route.js +++ b/app/api/custom-pages/[name]/route.js @@ -1,5 +1,6 @@ // GET /api/custom-pages/[name] — 公开单个页面 import pool from '@/lib/db'; +import { jsonWithEtag } from '@/lib/http-cache'; export async function GET(req, { params }) { try { @@ -10,7 +11,7 @@ export async function GET(req, { params }) { if (r.rows.length === 0) { return Response.json({ error: '页面不存在' }, { status: 404 }); } - return Response.json(r.rows[0]); + return jsonWithEtag(req, r.rows[0]); } catch { return Response.json({ error: '服务器错误' }, { status: 500 }); } diff --git a/app/api/custom-pages/route.js b/app/api/custom-pages/route.js index 5cd0b29..3fd4e10 100644 --- a/app/api/custom-pages/route.js +++ b/app/api/custom-pages/route.js @@ -1,12 +1,13 @@ // GET /api/custom-pages — 公开页面列表 import pool from '@/lib/db'; +import { jsonWithEtag } from '@/lib/http-cache'; -export async function GET() { +export async function GET(req) { try { const r = await pool.query( '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 { return Response.json({ error: '服务器错误' }, { status: 500 }); } diff --git a/app/api/links/route.js b/app/api/links/route.js index c6c77dc..0b95ecb 100644 --- a/app/api/links/route.js +++ b/app/api/links/route.js @@ -1,15 +1,16 @@ // GET /api/links, POST /api/links import pool from '@/lib/db'; import { getUser, requireAdmin } from '@/lib/auth'; +import { jsonWithEtag } from '@/lib/http-cache'; // 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存) export const dynamic = 'force-dynamic'; -export async function GET() { +export async function GET(req) { try { const r = await pool.query('SELECT * FROM friendly_links ORDER BY sort_order'); - return Response.json(r.rows); + return jsonWithEtag(req, r.rows); } catch { return Response.json({ error: '服务器错误' }, { status: 500 }); } diff --git a/app/api/posts/[id]/replies/route.js b/app/api/posts/[id]/replies/route.js index 8b89914..149b667 100644 --- a/app/api/posts/[id]/replies/route.js +++ b/app/api/posts/[id]/replies/route.js @@ -1,6 +1,7 @@ // GET /api/posts/[id]/replies, POST /api/posts/[id]/replies import pool from '@/lib/db'; import { getUser } from '@/lib/auth'; +import { jsonWithEtag } from '@/lib/http-cache'; export async function GET(req, { params }) { try { @@ -12,7 +13,7 @@ export async function GET(req, { params }) { ORDER BY r.created_at ASC`, [(await params).id] ); - return Response.json(r.rows); + return jsonWithEtag(req, r.rows); } catch { return Response.json({ error: '服务器错误' }, { status: 500 }); } diff --git a/app/api/posts/[id]/route.js b/app/api/posts/[id]/route.js index d4e5953..0248ae8 100644 --- a/app/api/posts/[id]/route.js +++ b/app/api/posts/[id]/route.js @@ -1,6 +1,7 @@ // GET /api/posts/[id], DELETE /api/posts/[id] import pool from '@/lib/db'; 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; @@ -21,7 +22,7 @@ export async function GET(req, { params }) { if (r.rows.length === 0) { return invalidId(); } - return Response.json(r.rows[0]); + return jsonWithEtag(req, r.rows[0]); } catch { return Response.json({ error: '服务器错误' }, { status: 500 }); } diff --git a/app/api/posts/route.js b/app/api/posts/route.js index a8eb54f..56db7bb 100644 --- a/app/api/posts/route.js +++ b/app/api/posts/route.js @@ -1,6 +1,7 @@ // GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= & 分页 import pool from '@/lib/db'; import { getUser } from '@/lib/auth'; +import { jsonWithEtag } from '@/lib/http-cache'; // 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存) export const dynamic = 'force-dynamic'; @@ -38,7 +39,7 @@ export async function GET(req) { LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2} `, [...params, limit, offset]); - return Response.json({ + return jsonWithEtag(req, { data: r.rows, pagination: { page, limit, total, totalPages: Math.ceil(total / limit) }, }); diff --git a/app/api/settings/route.js b/app/api/settings/route.js index e8aef6a..53a3b8d 100644 --- a/app/api/settings/route.js +++ b/app/api/settings/route.js @@ -1,23 +1,24 @@ // GET /api/settings, PUT /api/settings import pool from '@/lib/db'; import { getUser, requireAdmin } from '@/lib/auth'; +import { jsonWithEtag } from '@/lib/http-cache'; // 避免 GET 被静态优化导致 PUT 405(动态接口,不能缓存) export const dynamic = 'force-dynamic'; -export async function GET() { +export async function GET(req) { try { // 确保 forum_name 始终存在(未设置过则初始化默认值),前端拿到后显示 await pool.query( `INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify') 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 = {}; r.rows.forEach((row) => { settings[row.key] = row.value; }); // 兜底:即使插入失败也保证返回 forum_name if (!settings.forum_name) settings.forum_name = 'Forumlify'; - return Response.json(settings); + return jsonWithEtag(req, settings); } catch { return Response.json({ error: '服务器错误' }, { status: 500 }); } diff --git a/app/api/users/profile/[username]/route.js b/app/api/users/profile/[username]/route.js index bedd00d..f7d54c2 100644 --- a/app/api/users/profile/[username]/route.js +++ b/app/api/users/profile/[username]/route.js @@ -1,5 +1,6 @@ // GET /api/users/profile/:username — 用户公开信息(无需登录,用于用户主页) import pool from '@/lib/db'; +import { jsonWithEtag } from '@/lib/http-cache'; export async function GET(req, { params }) { const { username } = await params; @@ -14,7 +15,7 @@ export async function GET(req, { params }) { if (r.rows.length === 0) { return Response.json({ error: '用户不存在' }, { status: 404 }); } - return Response.json(r.rows[0]); + return jsonWithEtag(req, r.rows[0]); } catch { return Response.json({ error: '服务器错误' }, { status: 500 }); } diff --git a/app/globals.css b/app/globals.css index 7cede4d..f176eea 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1438,7 +1438,7 @@ svg { } [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 { diff --git a/lib/http-cache.js b/lib/http-cache.js new file mode 100644 index 0000000..99f9fe0 --- /dev/null +++ b/lib/http-cache.js @@ -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 }); +} diff --git a/next.config.js b/next.config.js index f45afd7..e0b2545 100644 --- a/next.config.js +++ b/next.config.js @@ -1,5 +1,7 @@ /** @type {import('next').NextConfig} */ const nextConfig = { + // 本地开发同时支持 localhost 和 127.0.0.1,避免客户端脚本被跨源保护拦截。 + allowedDevOrigins: ['127.0.0.1'], // Docker 部署用 standalone 输出;serverless(Vercel/CF Pages)不需要 ...(process.env.DOCKER ? { output: 'standalone' } : {}), // /uploads/* 由 API 路由提供(上传文件运行时新增,不进 public 构建快照) @@ -8,24 +10,6 @@ const nextConfig = { { 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; diff --git a/test/http-cache.test.js b/test/http-cache.test.js new file mode 100644 index 0000000..1ae680a --- /dev/null +++ b/test/http-cache.test.js @@ -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'] }); +});