Files
no-whatever/src/app/api/room/[id]/swipe/route.ts
T
kurihada 77d15f29e3 fix: 修复竞态条件、重置逻辑、无匹配终态等关键问题
- 用 Prisma $transaction 实现 atomicUpdateRoom,防止并发写入覆盖
- 新增 POST /api/room/[id]/reset 端点,修复"再来一轮"按钮死循环
- 新增 swipeCounts 字段追踪滑动进度,检测"无人匹配"终态
- 着陆页 handleCreate 增加 res.ok 检查,防止跳转到无效房间
- 匹配或无匹配后停止轮询,减少无效请求
2026-02-24 17:04:16 +08:00

63 lines
1.4 KiB
TypeScript

import { NextResponse } from "next/server";
import { atomicUpdateRoom } from "@/lib/store";
export async function POST(
req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params;
try {
const { userId, restaurantId, action } = await req.json();
if (!userId || restaurantId == null || !action) {
return NextResponse.json(
{ error: "userId, restaurantId, and action are required" },
{ status: 400 },
);
}
const rid = String(restaurantId);
const updated = await atomicUpdateRoom(id, (data) => {
if (action === "like") {
if (!data.likes[rid]) {
data.likes[rid] = [];
}
if (!data.likes[rid].includes(userId)) {
data.likes[rid].push(userId);
}
if (
data.users.length > 1 &&
data.likes[rid].length === data.users.length
) {
data.match = rid;
}
}
data.swipeCounts[userId] = (data.swipeCounts[userId] ?? 0) + 1;
return data;
});
if (!updated) {
return NextResponse.json(
{ error: "房间不存在或已过期" },
{ status: 404 },
);
}
return NextResponse.json({
match: updated.match,
likeCount: updated.likes[rid]?.length ?? 0,
});
} catch (e) {
console.error("Failed to process swipe:", e);
return NextResponse.json(
{ error: "操作失败" },
{ status: 500 },
);
}
}