清理revalidate冗余代码

This commit is contained in:
jingrow 2025-06-24 02:30:48 +08:00
parent a4e4de01d1
commit 7cb5ccec85
2 changed files with 2 additions and 25 deletions

View File

@ -1,52 +1,29 @@
import { revalidatePath } from 'next/cache'; import { revalidatePath } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server'; import { NextRequest, NextResponse } from 'next/server';
/**
* 按需重新验证 API 路由
* 当后端内容更新时通过调用此 API 来手动触发特定页面的重新生成
*
* 调用方式:
* POST /api/revalidate
* Headers:
* Content-Type: application/json
* x-revalidate-secret: YOUR_SECRET_TOKEN
* Body:
* {
* "path": "/page-to-revalidate"
* }
*/
export async function POST(request) { export async function POST(request) {
// 1. 从请求头中获取密钥 // 1. 从请求头中获取密钥
const secret = request.headers.get('x-revalidate-secret'); const secret = request.headers.get('x-revalidate-secret');
// 2. 验证密钥 // 2. 验证密钥
// 为了安全,这个密钥应该存储在环境变量中,并且不能硬编码。
if (secret !== process.env.REVALIDATE_TOKEN) { if (secret !== process.env.REVALIDATE_TOKEN) {
console.warn('Invalid revalidate token received.');
return NextResponse.json({ message: 'Invalid token' }, { status: 401 }); return NextResponse.json({ message: 'Invalid token' }, { status: 401 });
} }
// 3. 从请求体中获取并记录需要重新验证的路径 // 3. 从请求体中获取需要重新验证的路径
const body = await request.json(); const body = await request.json();
const { path } = body; const { path } = body;
console.log('Revalidation request body:', body);
if (!path) { if (!path) {
console.warn('Revalidation request received without a path.');
return NextResponse.json({ message: 'Path is required' }, { status: 400 }); return NextResponse.json({ message: 'Path is required' }, { status: 400 });
} }
try { try {
// 4. 调用 Next.js 的 revalidatePath 函数 // 4. 调用 Next.js 的 revalidatePath 函数
// 这将清除指定路径的缓存,并在下次请求时重新生成页面。
revalidatePath(path); revalidatePath(path);
console.log(`Successfully revalidated path: ${path}`);
return NextResponse.json({ revalidated: true, now: Date.now() }); return NextResponse.json({ revalidated: true, now: Date.now() });
} catch (error) { } catch (error) {
// 5. 如果发生错误,返回错误信息 // 5. 如果发生错误,返回错误信息
console.error(`Error revalidating path: ${path}`, error);
return NextResponse.json( return NextResponse.json(
{ message: 'Error revalidating', error: error.message }, { message: 'Error revalidating', error: error.message },
{ status: 500 } { status: 500 }

View File

@ -1,7 +1,7 @@
import DynamicListPageUI from './DynamicListPageUI'; import DynamicListPageUI from './DynamicListPageUI';
import { getPageData } from '@/utils/data'; import { getPageData } from '@/utils/data';
export default async function DynamicListPage({ slugArr, basePath, columns, pageSize = 10, searchParams }) { export default async function DynamicListPage({ slugArr, basePath, columns, pageSize = 12, searchParams }) {
// await searchParams // await searchParams
const resolvedSearchParams = await searchParams; const resolvedSearchParams = await searchParams;
// //