refactor: 提取 requireUserId/requireUser/requireMembership 校验工具

- 新增 requireUserId:统一 14 处 userId 非空校验,返回 401
- 新增 requireUser:统一 4 处用户存在性检查,返回 404
- validateMembership 升级为 requireMembership,直接抛 403
- 混合校验拆分为 auth(401) + 字段(400),状态码更准确
This commit is contained in:
2026-02-26 18:17:17 +08:00
parent 0595887480
commit 19edcaeeb5
15 changed files with 67 additions and 56 deletions
+6 -5
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { apiHandler, ApiError } from "@/lib/api";
import { apiHandler, ApiError, requireUserId, requireUser } from "@/lib/api";
export const GET = apiHandler(async (req) => {
const userId = req.nextUrl.searchParams.get("userId");
@@ -24,10 +24,10 @@ export const GET = apiHandler(async (req) => {
export const POST = apiHandler(async (req) => {
const { userId, restaurant } = await req.json();
if (!userId || !restaurant) throw new ApiError("缺少必要字段");
requireUserId(userId);
if (!restaurant) throw new ApiError("缺少必要字段");
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) throw new ApiError("请先设置个人资料", 404);
await requireUser(userId);
const existing = await prisma.favorite.findFirst({
where: {
@@ -53,7 +53,8 @@ export const POST = apiHandler(async (req) => {
export const DELETE = apiHandler(async (req) => {
const { userId, favoriteId } = await req.json();
if (!userId || !favoriteId) throw new ApiError("缺少必要字段");
requireUserId(userId);
if (!favoriteId) throw new ApiError("缺少必要字段");
const fav = await prisma.favorite.findUnique({ where: { id: favoriteId } });
if (!fav || fav.userId !== userId) throw new ApiError("收藏不存在", 404);