mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-03 09:19:35 +08:00
fix: 标签与练习领域接口补充请求参数校验
为以下路由补充 zod 校验,失败返回 400(沿用原有错误文案风格): - POST /api/tags:createTagSchema 校验 name/subject/parentId/tagSet - DELETE /api/tags:deleteTagQuerySchema 校验 id 查询参数 - POST /api/notebooks:createNotebookSchema 校验 name/stage/subjectKey/tagSet - PUT /api/notebooks/[id]:updateNotebookSchema 校验 name - POST /api/practice/generate:generatePracticeSchema 校验 errorItemId/language/difficulty - GET /api/review/due:reviewDueQuerySchema 校验 subjectId/page/pageSize 新增集成测试用例: - practice.test.ts:缺少 errorItemId、difficulty 非法时返回 400 - review.test.ts:page/pageSize 为非数字时返回 400 - tags.test.ts:POST 缺少 name/subject、parentId 非法类型、DELETE 缺少 id 时返回 400
This commit is contained in:
@@ -302,6 +302,34 @@ describe('/api/practice', () => {
|
||||
expect(data.message).toBe('Item not found');
|
||||
});
|
||||
|
||||
it('缺少 errorItemId 时返回 400', async () => {
|
||||
const request = new Request('http://localhost/api/practice/generate', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ language: 'zh' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
const response = await GENERATE_POST(request);
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(data.message).toBe('errorItemId is required');
|
||||
expect(mocks.mockAIService.generateSimilarQuestion).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('difficulty 取值非法时返回 400', async () => {
|
||||
const request = new Request('http://localhost/api/practice/generate', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ errorItemId: 'error-item-1', language: 'zh', difficulty: 'extreme' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
const response = await GENERATE_POST(request);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(mocks.mockAIService.generateSimilarQuestion).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('应该正确解析知识点标签', async () => {
|
||||
mocks.mockPrismaErrorItem.findUnique.mockResolvedValue(mockErrorItem);
|
||||
mocks.mockAIService.generateSimilarQuestion.mockResolvedValue({
|
||||
|
||||
@@ -69,4 +69,11 @@ describe('GET /api/review/due', () => {
|
||||
const response = await get();
|
||||
expect(response.status).toBe(401);
|
||||
});
|
||||
|
||||
it('page 或 pageSize 为非数字时返回 400', async () => {
|
||||
for (const query of ['?page=abc', '?pageSize=xyz', '?page=-1', '?pageSize=0']) {
|
||||
const response = await get(query);
|
||||
expect(response.status).toBe(400);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -345,4 +345,56 @@ describe('/api/tags', () => {
|
||||
expect(data.suggestions).not.toContain('函数');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/tags (创建标签)', () => {
|
||||
beforeEach(() => {
|
||||
mocks.mockGetServerSession.mockResolvedValue({ user: { email: 'user@example.com' }, expires: '2099-01-01' });
|
||||
mocks.mockPrismaUser.findUnique.mockResolvedValue({ id: 'user-1', email: 'user@example.com' });
|
||||
});
|
||||
|
||||
it('缺少 name 或 subject 时返回 400', async () => {
|
||||
const { POST } = await import('@/app/api/tags/route');
|
||||
for (const body of [{ name: '标签' }, { subject: 'math' }, { name: '', subject: 'math' }]) {
|
||||
const response = await POST(new Request('http://localhost/api/tags', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
expect(response.status).toBe(400);
|
||||
}
|
||||
});
|
||||
|
||||
it('parentId 为 null、tagSet 为空串时按缺省处理,不返回 400', async () => {
|
||||
const { POST } = await import('@/app/api/tags/route');
|
||||
const response = await POST(new Request('http://localhost/api/tags', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name: '标签', subject: 'math', parentId: null, tagSet: ' ' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
expect(response.status).not.toBe(400);
|
||||
});
|
||||
|
||||
it('parentId 为非法类型时返回 400', async () => {
|
||||
const { POST } = await import('@/app/api/tags/route');
|
||||
const response = await POST(new Request('http://localhost/api/tags', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name: '标签', subject: 'math', parentId: 123 }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}));
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /api/tags (删除标签)', () => {
|
||||
beforeEach(() => {
|
||||
mocks.mockGetServerSession.mockResolvedValue({ user: { email: 'user@example.com' }, expires: '2099-01-01' });
|
||||
mocks.mockPrismaUser.findUnique.mockResolvedValue({ id: 'user-1', email: 'user@example.com' });
|
||||
});
|
||||
|
||||
it('缺少 id 查询参数时返回 400', async () => {
|
||||
const { DELETE } = await import('@/app/api/tags/route');
|
||||
const response = await DELETE(new Request('http://localhost/api/tags'));
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { prisma } from "@/lib/prisma";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { forbidden, notFound, badRequest, internalError } from "@/lib/api-errors";
|
||||
import { updateNotebookSchema } from "@/lib/schemas/notebooks";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
|
||||
const logger = createLogger('api:notebooks:id');
|
||||
@@ -74,12 +75,11 @@ async function handlePut(
|
||||
return forbidden("Not authorized to update this notebook");
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const { name } = body;
|
||||
|
||||
if (!name || !name.trim()) {
|
||||
const parsed = updateNotebookSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return badRequest("Notebook name is required");
|
||||
}
|
||||
const { name } = parsed.data;
|
||||
|
||||
const updated = await prisma.subject.update({
|
||||
where: { id },
|
||||
|
||||
@@ -4,7 +4,8 @@ import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { badRequest, conflict, internalError } from "@/lib/api-errors";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { isValidNotebookScope, stageFromEducationStage, STAGE_SUBJECTS, type NotebookSubject } from "@/lib/notebook-scope";
|
||||
import { createNotebookSchema } from "@/lib/schemas/notebooks";
|
||||
import { stageFromEducationStage, STAGE_SUBJECTS, type NotebookSubject } from "@/lib/notebook-scope";
|
||||
|
||||
const logger = createLogger('api:notebooks');
|
||||
|
||||
@@ -84,18 +85,17 @@ export const GET = withUser(async (req, ctx) => {
|
||||
* 创建新错题本
|
||||
*/
|
||||
async function handlePost(req: Request, { user }: AuthenticatedContext) {
|
||||
const body = await req.json();
|
||||
const { name, stage, subjectKey, tagSet } = body;
|
||||
|
||||
if (typeof name !== "string" || !name.trim()) {
|
||||
return badRequest("Notebook name is required");
|
||||
}
|
||||
// 学段和学科只能在创建时选择,之后不可修改
|
||||
if (!isValidNotebookScope(stage, subjectKey)) {
|
||||
const parsed = createNotebookSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
if (issue?.path[0] === 'name') {
|
||||
return badRequest("Notebook name is required");
|
||||
}
|
||||
return badRequest("A valid stage and subject are required");
|
||||
}
|
||||
const { name, stage, subjectKey } = parsed.data;
|
||||
// 标签体系:非空字符串,默认 default
|
||||
const finalTagSet = typeof tagSet === 'string' && tagSet.trim() ? tagSet.trim() : 'default';
|
||||
const finalTagSet = parsed.data.tagSet?.trim() || 'default';
|
||||
|
||||
// 检查是否已存在同名错题本
|
||||
const existing = await prisma.subject.findUnique({
|
||||
|
||||
@@ -3,7 +3,8 @@ import { prisma } from "@/lib/prisma";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { getAIService } from "@/lib/ai";
|
||||
import { notFound, internalError } from "@/lib/api-errors";
|
||||
import { badRequest, notFound, internalError } from "@/lib/api-errors";
|
||||
import { generatePracticeSchema } from "@/lib/schemas/practice";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { describeQuestion, trackBackgroundTask } from "@/lib/background-tasks";
|
||||
import { parseLastPractice, serializeLastPractice } from "@/lib/last-practice";
|
||||
@@ -45,7 +46,11 @@ export const GET = withUser(handleGet);
|
||||
|
||||
async function handlePostInner(req: Request, { user }: AuthenticatedContext) {
|
||||
try {
|
||||
const { errorItemId, language, difficulty } = await req.json();
|
||||
const parsed = generatePracticeSchema.safeParse(await req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return badRequest("errorItemId is required");
|
||||
}
|
||||
const { errorItemId, language, difficulty } = parsed.data;
|
||||
|
||||
const errorItemWithSubject = await prisma.errorItem.findUnique({
|
||||
where: { id: errorItemId },
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { withUser } from "@/lib/api-handler";
|
||||
import type { AuthenticatedContext } from "@/lib/api-handler";
|
||||
import { internalError } from "@/lib/api-errors";
|
||||
import { internalError, badRequest } from "@/lib/api-errors";
|
||||
import { getAppTimeZone } from "@/lib/config";
|
||||
import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, MIN_PAGE_SIZE } from "@/lib/constants/pagination";
|
||||
import { reviewDueQuerySchema } from "@/lib/schemas/practice";
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { getMasteryThreshold } from "@/lib/mastery";
|
||||
import { PRACTICE_RECORD_COUNT, masteryStatusOf } from "@/lib/mastery-status";
|
||||
@@ -15,9 +16,17 @@ const logger = createLogger('api:review:due');
|
||||
/** 今日待复习:按作答历史推算到期的错题,最早到期的排在前面 */
|
||||
async function handleGet(req: Request, { user }: AuthenticatedContext) {
|
||||
const { searchParams } = new URL(req.url);
|
||||
const subjectId = searchParams.get("subjectId");
|
||||
const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10) || 1);
|
||||
const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(MIN_PAGE_SIZE, parseInt(searchParams.get("pageSize") || String(DEFAULT_PAGE_SIZE), 10) || DEFAULT_PAGE_SIZE));
|
||||
const parsedQuery = reviewDueQuerySchema.safeParse({
|
||||
subjectId: searchParams.get("subjectId") ?? undefined,
|
||||
page: searchParams.get("page") ?? undefined,
|
||||
pageSize: searchParams.get("pageSize") ?? undefined,
|
||||
});
|
||||
if (!parsedQuery.success) {
|
||||
return badRequest("Invalid query parameters");
|
||||
}
|
||||
const { subjectId } = parsedQuery.data;
|
||||
const page = Math.max(1, parsedQuery.data.page ?? 1);
|
||||
const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(MIN_PAGE_SIZE, parsedQuery.data.pageSize ?? DEFAULT_PAGE_SIZE));
|
||||
|
||||
try {
|
||||
const timeZone = getAppTimeZone();
|
||||
|
||||
@@ -9,6 +9,7 @@ import { NextRequest, NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { withUser } from '@/lib/api-handler';
|
||||
import type { AuthenticatedContext } from '@/lib/api-handler';
|
||||
import { createTagSchema, deleteTagQuerySchema } from '@/lib/schemas/tags';
|
||||
import { createLogger } from '@/lib/logger';
|
||||
import type { KnowledgeTag } from '@prisma/client';
|
||||
|
||||
@@ -148,16 +149,16 @@ export const GET = withUser(async (req, ctx) => {
|
||||
* tagSet 缺省为 'default';父节点必须属于同一学科和同一标签体系
|
||||
*/
|
||||
async function handlePost(request: NextRequest, { user }: AuthenticatedContext) {
|
||||
const body = await request.json();
|
||||
const { name, subject, parentId } = body;
|
||||
const tagSet = typeof body.tagSet === 'string' && body.tagSet.trim() ? body.tagSet.trim() : 'default';
|
||||
|
||||
if (typeof name !== 'string' || !name.trim() || typeof subject !== 'string' || !subject) {
|
||||
const parsed = createTagSchema.safeParse(await request.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
if (issue?.path[0] === 'parentId') {
|
||||
return NextResponse.json({ error: 'Invalid parentId' }, { status: 400 });
|
||||
}
|
||||
return NextResponse.json({ error: 'Name and subject are required' }, { status: 400 });
|
||||
}
|
||||
if (parentId !== undefined && parentId !== null && typeof parentId !== 'string') {
|
||||
return NextResponse.json({ error: 'Invalid parentId' }, { status: 400 });
|
||||
}
|
||||
const { name, subject, parentId } = parsed.data;
|
||||
const tagSet = parsed.data.tagSet?.trim() || 'default';
|
||||
|
||||
// 父节点须是同一学科、同一体系下当前用户可见的标签,避免挂到其他体系或别人的标签下
|
||||
if (parentId) {
|
||||
@@ -222,11 +223,11 @@ export const POST = withUser(async (req, ctx) => {
|
||||
*/
|
||||
async function handleDelete(request: NextRequest, { user }: AuthenticatedContext) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tagId = searchParams.get('id');
|
||||
|
||||
if (!tagId) {
|
||||
const parsed = deleteTagQuerySchema.safeParse({ id: searchParams.get('id') });
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Tag ID is required' }, { status: 400 });
|
||||
}
|
||||
const { id: tagId } = parsed.data;
|
||||
|
||||
// 只能删除自己的自定义标签
|
||||
const tag = await prisma.knowledgeTag.findFirst({
|
||||
|
||||
19
src/lib/schemas/notebooks.ts
Normal file
19
src/lib/schemas/notebooks.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { z } from "zod";
|
||||
import { isValidNotebookScope, type NotebookStage, type NotebookSubject } from "@/lib/notebook-scope";
|
||||
|
||||
/** POST /api/notebooks 请求体 */
|
||||
export const createNotebookSchema = z.object({
|
||||
name: z.string().trim().min(1),
|
||||
stage: z.string(),
|
||||
subjectKey: z.string(),
|
||||
/** 缺省或空白时由路由回退为 default */
|
||||
tagSet: z.string().optional(),
|
||||
}).refine(
|
||||
(data) => isValidNotebookScope(data.stage as NotebookStage, data.subjectKey as NotebookSubject),
|
||||
{ message: "A valid stage and subject are required" }
|
||||
);
|
||||
|
||||
/** PUT /api/notebooks/[id] 请求体 */
|
||||
export const updateNotebookSchema = z.object({
|
||||
name: z.string().trim().min(1),
|
||||
});
|
||||
22
src/lib/schemas/practice.ts
Normal file
22
src/lib/schemas/practice.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const DIFFICULTIES = ["easy", "medium", "hard", "harder"] as const;
|
||||
|
||||
/** POST /api/practice/generate 请求体 */
|
||||
export const generatePracticeSchema = z.object({
|
||||
errorItemId: z.string().trim().min(1),
|
||||
language: z.enum(["zh", "en"]).optional(),
|
||||
difficulty: z.enum(DIFFICULTIES).optional(),
|
||||
});
|
||||
|
||||
/** GET /api/practice/generate 查询参数 */
|
||||
export const generatePracticeQuerySchema = z.object({
|
||||
errorItemId: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
/** GET /api/review/due 查询参数 */
|
||||
export const reviewDueQuerySchema = z.object({
|
||||
subjectId: z.string().trim().min(1).optional(),
|
||||
page: z.coerce.number().int().min(1).optional(),
|
||||
pageSize: z.coerce.number().int().min(1).optional(),
|
||||
});
|
||||
15
src/lib/schemas/tags.ts
Normal file
15
src/lib/schemas/tags.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** POST /api/tags 请求体 */
|
||||
export const createTagSchema = z.object({
|
||||
name: z.string().trim().min(1),
|
||||
subject: z.string().trim().min(1),
|
||||
parentId: z.string().nullish(),
|
||||
/** 缺省或空白时由路由回退为 default */
|
||||
tagSet: z.string().optional(),
|
||||
});
|
||||
|
||||
/** DELETE /api/tags 查询参数 */
|
||||
export const deleteTagQuerySchema = z.object({
|
||||
id: z.string().trim().min(1),
|
||||
});
|
||||
Reference in New Issue
Block a user