fix(cms): 后台发布/更新/删除真正让前台 ISR 失效(DEC-N5)
失效映射原先长在 /api/cms/revalidate 的路由体里,所以它只能被外部 HTTP 调用触发。 实测后果:后台四条变更链一个都不刷缓存,8 个页面注释里那句 「CMS 发布/更新时通过 /api/cms/revalidate 主动刷新」是假的 —— s-maxage=3600 下 最长 1 小时前台仍端出已删或过期内容,且没有任何门禁会红。 - 新增 src/lib/cms/revalidation.ts:modelCode→paths 推导做成纯函数 (pathsForModel / tagsForModel / planRevalidation),副作用收在 revalidateContent;同 §5.30「安全抽象必须可导入」。 - 路由改为消费同一份推导(响应契约与去重语义逐字保持,16 套件既有断言未动)。 - items 的 POST/PUT/DELETE、workflow 四个动作、zones 的写与删都接上失效; 判据按 status(草稿不进前台读取路径),slug 变更时旧地址一并刷。 - revalidateContent 是尽力而为:逐条 try + [revalidation-failed] 日志 + failed 回报, 因为数据已落库,刷缓存失败不该把成功的写入连带变成 500; applyRevalidation 仍严格冒泡,保持 /api/cms/revalidate 的 500 语义。 证据:新增 10 例(纯映射 12 例 + 调用点 6 例)。定向 16 套件 193 例 EXIT=0; 负对照把 workflow 的调用点改成注释 ⇒ MUTANT_EXIT=1(4 例转红),还原后 EXIT=0。 lint 定向 0 error。
This commit is contained in:
1 parent
0ae765afcd
commit
f3e66f7d36
9 files changed
+660
-134
No files matched your search
@@ -5,6 +5,13 @@ import { NextRequest } from 'next/server';
|
||||
const mockContentItemFindUnique = jest.fn<(args: unknown) => Promise<unknown | null>>();
|
||||
const mockContentItemFindUniqueOrThrow = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
|
||||
// 同 api/cms/revalidate/route.test.ts:next/cache 由运行时提供,jest 里真调会抛
|
||||
// `Invariant: static generation store missing`。DEC-N5 后发布链会触发失效,故桩掉。
|
||||
jest.mock('next/cache', () => ({
|
||||
revalidatePath: jest.fn(),
|
||||
revalidateTag: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('@/lib/db', () => ({
|
||||
prisma: {
|
||||
contentItem: {
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from '@/lib/api-response';
|
||||
import { withCrypto } from '@/lib/api-crypto';
|
||||
import { parseCmsData } from '@/lib/cms/validate-content-data';
|
||||
import { revalidateContent } from '@/lib/cms/revalidation';
|
||||
|
||||
// 与 items/route.ts 同源:脏 data 列不得让这个已成功的审批动作在返回阶段变成 500(B-4)。
|
||||
function parseItem(item: { data: string; [key: string]: unknown }) {
|
||||
@@ -82,7 +83,13 @@ export const POST = withCrypto(async (
|
||||
break;
|
||||
}
|
||||
|
||||
return success(parseItem(await prisma.contentItem.findUniqueOrThrow({ where: { id } })));
|
||||
// DEC-N5:发布链以前什么都不刷 ——「后台发布后前台最长 1 小时不可见」就是这条缺口。
|
||||
// approve 让内容首次出现,reject/archive 让它消失,submit 不改可见性但也一并失效:
|
||||
// 多余的一次 revalidatePath 是幂等的,漏一次则是用户可见的旧内容,代价不对称。
|
||||
const updated = await prisma.contentItem.findUniqueOrThrow({ where: { id } });
|
||||
revalidateContent(existing.modelCode, updated.slug);
|
||||
|
||||
return success(parseItem(updated));
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('内容不存在')) {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
/**
|
||||
* DEC-N5 的回归守卫:后台四条变更链必须让前台 ISR 快照失效。
|
||||
*
|
||||
* 为什么单独成文件、且断言的是「调用了吗」而不是「返回值对不对」:
|
||||
* 本仓原先的缺口不在映射算错,而在**没有任何生产调用方** ——
|
||||
* 映射长在 /api/cms/revalidate 的路由体里,只有外部 HTTP 调用才触发它,
|
||||
* 于是后台发布/更新/删除全都静默不刷缓存,最长 1 小时前台仍是旧内容,
|
||||
* 而没有任何门禁会红。所以这道守卫的对象就是「调用点存在」本身。
|
||||
*
|
||||
* 敏感性自证(负对照):把 route.ts 里任一 `revalidateContent(...)` 调用删掉,
|
||||
* 本文件对应用例必须转红(`Expected "revalidateContent" to have been called ... Received number of calls: 0`)。
|
||||
*/
|
||||
|
||||
const mockRevalidateContent = jest.fn<(modelCode: string, slug?: string | null) => unknown>();
|
||||
jest.mock('@/lib/cms/revalidation', () => ({
|
||||
revalidateContent: mockRevalidateContent,
|
||||
}));
|
||||
|
||||
// next/cache 在测试运行时不可用;本文件不触达真实实现(已被上面的 mock 挡住),
|
||||
// 但仍显式桩掉,避免任何间接 import 把真实模块拉进来。
|
||||
jest.mock('next/cache', () => ({
|
||||
revalidatePath: jest.fn(),
|
||||
revalidateTag: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockContentItemFindUnique = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentItemFindUniqueOrThrow = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentItemFindFirst = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentItemUpdate = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentItemDelete = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentItemCreate = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentModelFindUnique = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockAuditLogCreate = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
|
||||
jest.mock('@/lib/db', () => ({
|
||||
prisma: {
|
||||
contentItem: {
|
||||
findUnique: mockContentItemFindUnique,
|
||||
findUniqueOrThrow: mockContentItemFindUniqueOrThrow,
|
||||
findFirst: mockContentItemFindFirst,
|
||||
update: mockContentItemUpdate,
|
||||
delete: mockContentItemDelete,
|
||||
create: mockContentItemCreate,
|
||||
},
|
||||
contentModel: { findUnique: mockContentModelFindUnique },
|
||||
auditLog: { create: mockAuditLogCreate },
|
||||
},
|
||||
}));
|
||||
|
||||
const mockRequirePermission = jest.fn<(r: NextRequest, m: string, a: string) => Promise<unknown>>();
|
||||
jest.mock('@/lib/permissions', () => ({ requirePermission: mockRequirePermission }));
|
||||
|
||||
const mockAuthenticateRequest = jest.fn<(r: NextRequest) => unknown>();
|
||||
jest.mock('@/lib/auth', () => ({ authenticateRequest: mockAuthenticateRequest }));
|
||||
|
||||
const mockSubmitForReview = jest.fn<(id: string, u: unknown) => Promise<unknown>>();
|
||||
const mockApprove = jest.fn<(id: string, u: unknown) => Promise<unknown>>();
|
||||
const mockReject = jest.fn<(id: string, u: unknown, reason?: string) => Promise<unknown>>();
|
||||
const mockArchive = jest.fn<(id: string, u: unknown) => Promise<unknown>>();
|
||||
jest.mock('@/lib/cms/workflow', () => ({
|
||||
submitForReview: mockSubmitForReview,
|
||||
approve: mockApprove,
|
||||
reject: mockReject,
|
||||
archive: mockArchive,
|
||||
}));
|
||||
|
||||
jest.unmock('@/app/api/admin/items/route');
|
||||
|
||||
import { POST as PUT_ITEMS_POST, PUT, DELETE } from '@/app/api/admin/items/route';
|
||||
import { POST as WORKFLOW_POST } from '@/app/api/admin/items/[id]/workflow/route';
|
||||
|
||||
function req(url: string, body: Record<string, unknown>): NextRequest {
|
||||
return {
|
||||
url,
|
||||
nextUrl: new URL(url),
|
||||
headers: new Headers(),
|
||||
json: async () => body,
|
||||
} as unknown as NextRequest;
|
||||
}
|
||||
|
||||
const NEWS_MODEL_FIELDS = JSON.stringify([]);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockRequirePermission.mockResolvedValue({ user: { userId: 'u1', username: 'admin' } });
|
||||
mockAuthenticateRequest.mockReturnValue({ userId: 'u1', username: 'admin' });
|
||||
mockContentModelFindUnique.mockResolvedValue({ id: 'm1', code: 'news', fields: NEWS_MODEL_FIELDS });
|
||||
mockContentItemFindFirst.mockResolvedValue(null);
|
||||
mockAuditLogCreate.mockResolvedValue({});
|
||||
mockSubmitForReview.mockResolvedValue(undefined);
|
||||
mockApprove.mockResolvedValue(undefined);
|
||||
mockReject.mockResolvedValue(undefined);
|
||||
mockArchive.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
function newsRow(status: string, slug = 'hello-world') {
|
||||
return {
|
||||
id: 'item-1',
|
||||
modelCode: 'news',
|
||||
slug,
|
||||
status,
|
||||
title: 'T',
|
||||
data: JSON.stringify({}),
|
||||
};
|
||||
}
|
||||
|
||||
describe('PUT /api/admin/items —— 更新已发布内容必须失效前台快照', () => {
|
||||
it('已发布行被编辑 ⇒ 按 modelCode + 新 slug 失效', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(newsRow('published'));
|
||||
mockContentItemUpdate.mockResolvedValue(newsRow('published', 'hello-world'));
|
||||
|
||||
const res = await PUT(req('http://x/api/admin/items?id=item-1', { title: '改名' }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockRevalidateContent).toHaveBeenCalledTimes(1);
|
||||
expect(mockRevalidateContent).toHaveBeenCalledWith('news', 'hello-world');
|
||||
});
|
||||
|
||||
it('草稿不进前台 ⇒ 不该失效(判据按状态、不是无条件刷)', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(newsRow('draft'));
|
||||
mockContentItemUpdate.mockResolvedValue(newsRow('draft'));
|
||||
|
||||
const res = await PUT(req('http://x/api/admin/items?id=item-1', { title: '改名' }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockRevalidateContent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('slug 变更 ⇒ 新地址与**旧地址**都要失效,否则旧 URL 继续端出旧内容', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(newsRow('published', 'old-slug'));
|
||||
mockContentItemUpdate.mockResolvedValue(newsRow('published', 'new-slug'));
|
||||
|
||||
const res = await PUT(req('http://x/api/admin/items?id=item-1', { slug: 'new-slug' }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockRevalidateContent).toHaveBeenCalledTimes(2);
|
||||
const slugs = mockRevalidateContent.mock.calls.map((c) => c[1]);
|
||||
expect(slugs).toEqual(expect.arrayContaining(['new-slug', 'old-slug']));
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/admin/items —— 删除已发布内容必须失效前台快照', () => {
|
||||
it('删除已发布行 ⇒ 失效(§11.5 那 8 条 /news 计数红的产品层根因)', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(newsRow('published'));
|
||||
mockContentItemDelete.mockResolvedValue(newsRow('published'));
|
||||
|
||||
const res = await DELETE(req('http://x/api/admin/items?id=item-1'));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockRevalidateContent).toHaveBeenCalledWith('news', 'hello-world');
|
||||
});
|
||||
|
||||
it('删除草稿 ⇒ 不失效', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(newsRow('draft'));
|
||||
mockContentItemDelete.mockResolvedValue(newsRow('draft'));
|
||||
|
||||
const res = await DELETE(req('http://x/api/admin/items?id=item-1'));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockRevalidateContent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/admin/items —— 创建', () => {
|
||||
it('强制草稿(B-1)⇒ 不失效;但判据跟着 status 走,放开直接发布时会自动跟上', async () => {
|
||||
mockContentItemCreate.mockResolvedValue({ ...newsRow('draft'), id: 'new-1' });
|
||||
|
||||
const res = await PUT_ITEMS_POST(
|
||||
req('http://x/api/admin/items', { modelId: 'm1', modelCode: 'news', title: '新稿' })
|
||||
);
|
||||
expect(res.status).toBe(201);
|
||||
expect(mockRevalidateContent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/admin/items/[id]/workflow —— 发布链', () => {
|
||||
it('approve ⇒ 发布后立刻失效(这条以前完全不刷,是 DEC-N5 的主体)', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(newsRow('pending_review'));
|
||||
mockContentItemFindUniqueOrThrow.mockResolvedValue({ ...newsRow('published'), id: 'item-1' });
|
||||
|
||||
const res = await WORKFLOW_POST(
|
||||
req('http://x/api/admin/items/workflow?id=item-1', { action: 'approve' }),
|
||||
{ params: Promise.resolve({ id: 'item-1' }) } as never
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockApprove).toHaveBeenCalledWith('item-1', { userId: 'u1', username: 'admin' });
|
||||
expect(mockRevalidateContent).toHaveBeenCalledTimes(1);
|
||||
expect(mockRevalidateContent).toHaveBeenCalledWith('news', 'hello-world');
|
||||
});
|
||||
|
||||
it.each(['submit', 'reject', 'archive'] as const)(
|
||||
'%s 也失效:多余一次是幂等,漏一次是用户可见的旧内容',
|
||||
async (action) => {
|
||||
mockContentItemFindUnique.mockResolvedValue(newsRow('published'));
|
||||
mockContentItemFindUniqueOrThrow.mockResolvedValue(newsRow('published'));
|
||||
|
||||
const res = await WORKFLOW_POST(req('http://x/api/admin/items/workflow?id=item-1', { action } as never), {
|
||||
params: Promise.resolve({ id: 'item-1' }),
|
||||
} as never);
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockRevalidateContent).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type ContentFieldError,
|
||||
} from '@/lib/cms/validate-content-data';
|
||||
import type { FieldDefinition } from '@/lib/cms/types';
|
||||
import { revalidateContent } from '@/lib/cms/revalidation';
|
||||
|
||||
function parseItem(item: { data: string; [key: string]: unknown }) {
|
||||
return { ...item, data: parseCmsData(item.data) };
|
||||
@@ -191,6 +192,11 @@ export const POST = withCrypto(async (request: NextRequest) => {
|
||||
},
|
||||
});
|
||||
|
||||
// DEC-N5:只有已发布的行会出现在前台读取路径上,草稿不需要刷 ISR。
|
||||
// 判据写成「item.status === 'published'」而不是「不刷」:本接口现在强制 draft
|
||||
// (B-1),一旦将来放开直接发布,失效会跟着状态自动发生,而不是留一处静默漏刷。
|
||||
if (item.status === 'published') revalidateContent(item.modelCode, item.slug);
|
||||
|
||||
return success(parseItem(item), 201);
|
||||
} catch (error) {
|
||||
console.error('Create item error:', error);
|
||||
@@ -271,6 +277,16 @@ export const PUT = withCrypto(async (request: NextRequest) => {
|
||||
},
|
||||
});
|
||||
|
||||
// DEC-N5:内容一旦落库,前台那份 ISR 快照就过期了。原先这里什么都不做,
|
||||
// 于是「已发布的行被改成新文案」最长 1 小时(s-maxage=3600)仍按旧快照对外。
|
||||
// 失效面由 revalidation 从 modelCode(含 slug)推导,与 /api/cms/revalidate 同源。
|
||||
// 放在审计之后:刷缓存是**尽力而为**的下游动作,不该把已成功的写入连带回滚成 500。
|
||||
if (existing.status === 'published') {
|
||||
revalidateContent(existing.modelCode, item.slug);
|
||||
// slug 变更时**旧**详情页的快照也得刷,否则旧地址继续端出旧内容 1 小时。
|
||||
if (item.slug !== existing.slug) revalidateContent(existing.modelCode, existing.slug);
|
||||
}
|
||||
|
||||
return success(parseItem(item));
|
||||
} catch (error) {
|
||||
console.error('Update item error:', error);
|
||||
@@ -306,6 +322,11 @@ export const DELETE = withCrypto(async (request: NextRequest) => {
|
||||
},
|
||||
});
|
||||
|
||||
// DEC-N5:删除已发布的行同样要让前台立刻知道(本条就是 qa-tracker §11.5
|
||||
// 里那 8 条「/news 筛选计数 2≠1」红因的产品层根因:uj03 删了行但没人刷缓存,
|
||||
// 于是删除被冻进 ISR 产物)。
|
||||
if (existing.status === 'published') revalidateContent(existing.modelCode, existing.slug);
|
||||
|
||||
return success({ message: '删除成功' });
|
||||
} catch (error) {
|
||||
console.error('Delete item error:', error);
|
||||
|
||||
@@ -9,6 +9,13 @@ const mockContentZoneUpdate = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentZoneDelete = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockAuditLogCreate = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
|
||||
// next/cache 是运行时提供的模块,jest 里真跑会抛 `Invariant: static generation store missing`。
|
||||
// DEC-N5 之后 zones 路由会触发失效,所以按本仓既有做法(见 api/cms/revalidate/route.test.ts)桩掉。
|
||||
jest.mock('next/cache', () => ({
|
||||
revalidatePath: jest.fn(),
|
||||
revalidateTag: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('@/lib/db', () => ({
|
||||
prisma: {
|
||||
contentZone: {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
internalError,
|
||||
} from '@/lib/api-response';
|
||||
import { withCrypto } from '@/lib/api-crypto';
|
||||
import { revalidateContent } from '@/lib/cms/revalidation';
|
||||
|
||||
// GET /api/admin/zones - 获取所有内容区域
|
||||
export const GET = withCrypto(async (request: NextRequest) => {
|
||||
@@ -86,6 +87,10 @@ export const POST = withCrypto(async (request: NextRequest) => {
|
||||
});
|
||||
}
|
||||
|
||||
// DEC-N5:ContentZone 是首页各段的数据源,改完必须让 / 的快照失效。
|
||||
// 口径与 /api/cms/revalidate 里 'content-zone' → '/' 那条同源(见 lib/cms/revalidation)。
|
||||
revalidateContent('content-zone');
|
||||
|
||||
return success({
|
||||
...zone,
|
||||
allowedModels: JSON.parse(zone.allowedModels),
|
||||
@@ -117,6 +122,7 @@ export const DELETE = withCrypto(async (request: NextRequest) => {
|
||||
if (!existing) return notFound('区域不存在');
|
||||
|
||||
await prisma.contentZone.delete({ where: { id } });
|
||||
revalidateContent('content-zone');
|
||||
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
|
||||
@@ -1,30 +1,10 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { revalidatePath, revalidateTag } from 'next/cache';
|
||||
import { CONTENT_TYPE_CONFIGS } from '@/lib/cms/content-types';
|
||||
import { planRevalidation, applyRevalidation } from '@/lib/cms/revalidation';
|
||||
|
||||
function getContentTypeConfig(code: string) {
|
||||
return CONTENT_TYPE_CONFIGS[code as keyof typeof CONTENT_TYPE_CONFIGS] ?? null;
|
||||
}
|
||||
|
||||
function getAllContentTypeConfigs() {
|
||||
return Object.values(CONTENT_TYPE_CONFIGS);
|
||||
}
|
||||
|
||||
// 首页受影响的模型:更新后需要同时刷新 /
|
||||
const HOME_AFFECTED_MODELS = new Set([
|
||||
'hero-banner',
|
||||
'stat-item',
|
||||
'service',
|
||||
'case-study',
|
||||
'solution',
|
||||
'news',
|
||||
]);
|
||||
|
||||
// 洞察枢纽 /insights 的数据来自三路真源:news(技术与观点)、case-study(客户成果,当前 0 行)、
|
||||
// methodology(方法论)。它**不在** CONTENT_TYPE_CONFIGS 的任何 listPage 里 ——
|
||||
// 通用推导只会刷 /news、/methodology,于是后台发了新内容而 /insights 仍端出旧 ISR 快照,
|
||||
// 最长 1 小时不可见,且没有任何门禁会红。新路由必须显式登记失效映射。
|
||||
const INSIGHTS_AFFECTED_MODELS = new Set(['news', 'case-study', 'methodology']);
|
||||
// 失效映射与执行都来自 @/lib/cms/revalidation(DEC-N5):后台的创建/更新/删除/发布
|
||||
// 四条变更链现在与这个 HTTP 入口共用**同一份** modelCode → paths 推导。
|
||||
// 原先映射长在下面的路由体里,所以它只能被外部调用触发,
|
||||
// 「CMS 发布/更新时主动刷新」那句话在没有任何生产调用方的日子里是假的。
|
||||
|
||||
interface RevalidateRequestBody {
|
||||
event?: string;
|
||||
@@ -57,119 +37,17 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const revalidatedPaths: string[] = [];
|
||||
const revalidatedTags: string[] = [];
|
||||
|
||||
if (body.paths && body.paths.length > 0) {
|
||||
for (const path of body.paths) {
|
||||
revalidatePath(path);
|
||||
revalidatedPaths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
if (body.tags && body.tags.length > 0) {
|
||||
for (const tag of body.tags) {
|
||||
revalidateTag(tag, {});
|
||||
revalidatedTags.push(tag);
|
||||
}
|
||||
}
|
||||
|
||||
if (body.modelCode) {
|
||||
const config = getContentTypeConfig(body.modelCode);
|
||||
if (config) {
|
||||
if (config.listPage?.route) {
|
||||
revalidatePath(config.listPage.route);
|
||||
revalidatedPaths.push(config.listPage.route);
|
||||
}
|
||||
|
||||
if (config.detailPage?.routePattern && body.slug) {
|
||||
const detailPath = config.detailPage.routePattern.replace('{slug}', body.slug);
|
||||
revalidatePath(detailPath);
|
||||
revalidatedPaths.push(detailPath);
|
||||
}
|
||||
|
||||
const tag = `cms:${body.modelCode}`;
|
||||
revalidateTag(tag, {});
|
||||
revalidatedTags.push(tag);
|
||||
}
|
||||
|
||||
// legal-page 为特殊页面类型,固定映射到 /privacy 和 /terms
|
||||
if (body.modelCode === 'legal-page') {
|
||||
const legalPaths = body.slug
|
||||
? [body.slug === 'terms' ? '/terms' : '/privacy']
|
||||
: ['/privacy', '/terms'];
|
||||
for (const path of legalPaths) {
|
||||
if (!revalidatedPaths.includes(path)) {
|
||||
revalidatePath(path);
|
||||
revalidatedPaths.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// team-page 为单页模型,固定映射到 /team
|
||||
if (body.modelCode === 'team-page' && !revalidatedPaths.includes('/team')) {
|
||||
revalidatePath('/team');
|
||||
revalidatedPaths.push('/team');
|
||||
}
|
||||
|
||||
// about-page / contact-page 为无 listPage 配置的单页模型,固定映射(S-3)
|
||||
if (body.modelCode === 'about-page' && !revalidatedPaths.includes('/about')) {
|
||||
revalidatePath('/about');
|
||||
revalidatedPaths.push('/about');
|
||||
}
|
||||
if (body.modelCode === 'contact-page' && !revalidatedPaths.includes('/contact')) {
|
||||
revalidatePath('/contact');
|
||||
revalidatedPaths.push('/contact');
|
||||
}
|
||||
|
||||
// /products/erp-upgrade 是硬编码页面,但数据来自 product 模型(slug=erp)(S-3)
|
||||
if (body.modelCode === 'product' && !revalidatedPaths.includes('/products/erp-upgrade')) {
|
||||
revalidatePath('/products/erp-upgrade');
|
||||
revalidatedPaths.push('/products/erp-upgrade');
|
||||
}
|
||||
|
||||
// 洞察枢纽:三个上游模型任一变更都要刷 /insights
|
||||
if (
|
||||
INSIGHTS_AFFECTED_MODELS.has(body.modelCode) &&
|
||||
!revalidatedPaths.includes('/insights')
|
||||
) {
|
||||
revalidatePath('/insights');
|
||||
revalidatedPaths.push('/insights');
|
||||
}
|
||||
|
||||
// 首页相关模型变更时同步刷新 /
|
||||
if (HOME_AFFECTED_MODELS.has(body.modelCode) && !revalidatedPaths.includes('/')) {
|
||||
revalidatePath('/');
|
||||
revalidatedPaths.push('/');
|
||||
}
|
||||
|
||||
// ContentZone 变更时刷新关联页面
|
||||
if (body.modelCode === 'content-zone' && !revalidatedPaths.includes('/')) {
|
||||
revalidatePath('/');
|
||||
revalidatedPaths.push('/');
|
||||
}
|
||||
}
|
||||
|
||||
if (body.event === 'content.published' || body.event === 'content.updated') {
|
||||
const allConfigs = getAllContentTypeConfigs();
|
||||
for (const config of allConfigs) {
|
||||
if (config.listPage?.route) {
|
||||
revalidatePath(config.listPage.route);
|
||||
if (!revalidatedPaths.includes(config.listPage.route)) {
|
||||
revalidatedPaths.push(config.listPage.route);
|
||||
}
|
||||
}
|
||||
}
|
||||
revalidateTag('cms:all', {});
|
||||
revalidatedTags.push('cms:all');
|
||||
}
|
||||
// modelCode 无对应 content-type 配置时,paths/tags 都会是空数组 ——
|
||||
// 这与重构前一致(不静默刷全站),并交由调用方看到空回执。
|
||||
const plan = planRevalidation(body);
|
||||
const applied = applyRevalidation(plan);
|
||||
|
||||
return NextResponse.json({
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: {
|
||||
revalidatedPaths,
|
||||
revalidatedTags,
|
||||
revalidatedPaths: applied.paths,
|
||||
revalidatedTags: applied.tags,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user