失效映射原先长在 /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。
196 lines
7.1 KiB
TypeScript
196 lines
7.1 KiB
TypeScript
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
|
||
import { NextRequest } from 'next/server';
|
||
|
||
// ─── Mock @/lib/db ────────────────────────────────────────────────────────
|
||
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: {
|
||
findUnique: mockContentItemFindUnique,
|
||
findUniqueOrThrow: mockContentItemFindUniqueOrThrow,
|
||
},
|
||
},
|
||
}));
|
||
|
||
// ─── Mock workflow service ────────────────────────────────────────────────
|
||
const mockSubmitForReview = jest.fn<(itemId: string, user: unknown) => Promise<unknown>>();
|
||
const mockApprove = jest.fn<(itemId: string, user: unknown) => Promise<unknown>>();
|
||
const mockReject = jest.fn<(itemId: string, user: unknown, reason?: string) => Promise<unknown>>();
|
||
const mockArchive = jest.fn<(itemId: string, user: unknown) => Promise<unknown>>();
|
||
|
||
jest.mock('@/lib/cms/workflow', () => ({
|
||
submitForReview: mockSubmitForReview,
|
||
approve: mockApprove,
|
||
reject: mockReject,
|
||
archive: mockArchive,
|
||
}));
|
||
|
||
// ─── Mock permissions ─────────────────────────────────────────────────────
|
||
const mockRequirePermission = jest.fn<
|
||
(request: NextRequest, modelCode: string, action: string) => Promise<unknown>
|
||
>();
|
||
|
||
jest.mock('@/lib/permissions', () => ({
|
||
requirePermission: mockRequirePermission,
|
||
}));
|
||
|
||
// Q-8:workflow POST 现会先 authenticateRequest 再探存在性;默认给有效会话。
|
||
const mockAuthenticateRequest = jest.fn<(request: NextRequest) => unknown>();
|
||
jest.mock('@/lib/auth', () => ({
|
||
authenticateRequest: mockAuthenticateRequest,
|
||
}));
|
||
|
||
jest.unmock('./route');
|
||
|
||
import { POST } from './route';
|
||
|
||
function createMockRequest(body: Record<string, unknown>): NextRequest {
|
||
return {
|
||
headers: new Headers(),
|
||
url: 'http://localhost:3000/api/admin/items/item-1/workflow',
|
||
json: async () => body,
|
||
} as unknown as NextRequest;
|
||
}
|
||
|
||
function mockAuthorized(action: 'update' | 'publish' = 'update') {
|
||
mockRequirePermission.mockResolvedValue({
|
||
user: { userId: 'user-1', username: 'editor', role: action === 'publish' ? 'reviewer' : 'editor' },
|
||
});
|
||
}
|
||
|
||
const mockItem = {
|
||
id: 'item-1',
|
||
modelId: 'model-1',
|
||
modelCode: 'news',
|
||
title: '测试新闻',
|
||
slug: 'test-news',
|
||
locale: 'zh-CN',
|
||
status: 'draft',
|
||
data: '{}',
|
||
version: 1,
|
||
sortOrder: 0,
|
||
createdBy: 'editor',
|
||
updatedBy: 'editor',
|
||
createdAt: new Date('2026-01-01'),
|
||
updatedAt: new Date('2026-01-01'),
|
||
};
|
||
|
||
const mockUpdatedItem = { ...mockItem, status: 'review', version: 2 };
|
||
|
||
beforeEach(() => {
|
||
jest.clearAllMocks();
|
||
mockContentItemFindUnique.mockResolvedValue(mockItem);
|
||
mockContentItemFindUniqueOrThrow.mockResolvedValue(mockUpdatedItem);
|
||
mockAuthenticateRequest.mockReturnValue({ userId: 'user-1', username: 'editor', role: 'editor' });
|
||
});
|
||
|
||
describe('POST /api/admin/items/[id]/workflow', () => {
|
||
it('returns 400 when action is missing', async () => {
|
||
mockAuthorized();
|
||
const request = createMockRequest({});
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'item-1' }) });
|
||
const body = await response.json();
|
||
|
||
expect(response.status).toBe(400);
|
||
expect(body.error).toBe('缺少 action 参数');
|
||
});
|
||
|
||
it('returns 400 for invalid action', async () => {
|
||
mockAuthorized();
|
||
const request = createMockRequest({ action: 'publish' });
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'item-1' }) });
|
||
const body = await response.json();
|
||
|
||
expect(response.status).toBe(400);
|
||
expect(body.error).toContain('非法的 action');
|
||
});
|
||
|
||
it('returns 404 when item not found', async () => {
|
||
mockAuthorized();
|
||
mockContentItemFindUnique.mockResolvedValue(null);
|
||
const request = createMockRequest({ action: 'submit' });
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'missing' }) });
|
||
const body = await response.json();
|
||
|
||
expect(response.status).toBe(404);
|
||
expect(body.error).toBe('内容不存在');
|
||
});
|
||
|
||
// Q-8:匿名调用者不得用「404 vs 401」枚举 ID —— 认证须先于存在性探针。
|
||
it('rejects an unauthenticated workflow with 401 WITHOUT probing item existence', async () => {
|
||
mockAuthenticateRequest.mockReturnValue(null);
|
||
const request = createMockRequest({ action: 'submit' });
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'item-1' }) });
|
||
|
||
expect(response.status).toBe(401);
|
||
expect(mockContentItemFindUnique).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('submit requires update permission', async () => {
|
||
mockAuthorized('update');
|
||
const request = createMockRequest({ action: 'submit' });
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'item-1' }) });
|
||
|
||
expect(response.status).toBe(200);
|
||
expect(mockSubmitForReview).toHaveBeenCalledWith(
|
||
'item-1',
|
||
expect.objectContaining({ username: 'editor' })
|
||
);
|
||
expect(mockRequirePermission).toHaveBeenCalledWith(
|
||
request,
|
||
'news',
|
||
'update'
|
||
);
|
||
});
|
||
|
||
it('approve requires publish permission', async () => {
|
||
mockAuthorized('publish');
|
||
const request = createMockRequest({ action: 'approve' });
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'item-1' }) });
|
||
|
||
expect(response.status).toBe(200);
|
||
expect(mockApprove).toHaveBeenCalledWith(
|
||
'item-1',
|
||
expect.objectContaining({ username: 'editor' })
|
||
);
|
||
expect(mockRequirePermission).toHaveBeenCalledWith(
|
||
request,
|
||
'news',
|
||
'publish'
|
||
);
|
||
});
|
||
|
||
it('reject passes reason to workflow service', async () => {
|
||
mockAuthorized('publish');
|
||
const request = createMockRequest({ action: 'reject', reason: '需要修改' });
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'item-1' }) });
|
||
|
||
expect(response.status).toBe(200);
|
||
expect(mockReject).toHaveBeenCalledWith(
|
||
'item-1',
|
||
expect.objectContaining({ username: 'editor' }),
|
||
'需要修改'
|
||
);
|
||
});
|
||
|
||
it('returns validation error on illegal transition', async () => {
|
||
mockAuthorized('publish');
|
||
mockApprove.mockRejectedValue(new Error('当前状态 draft 不允许审核通过'));
|
||
const request = createMockRequest({ action: 'approve' });
|
||
const response = await POST(request, { params: Promise.resolve({ id: 'item-1' }) });
|
||
const body = await response.json();
|
||
|
||
expect(response.status).toBe(400);
|
||
expect(body.error).toBe('当前状态 draft 不允许审核通过');
|
||
});
|
||
});
|