fix: 移除静默 fallback 数据,API 失败时明确提示用户

This commit is contained in:
2026-02-24 21:16:55 +08:00
parent 07ffe42176
commit 43d3ff0fa3
2 changed files with 56 additions and 47 deletions
+48 -40
View File
@@ -1,7 +1,6 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { createRoom } from "@/lib/store"; import { createRoom } from "@/lib/store";
import { Restaurant } from "@/types"; import { Restaurant } from "@/types";
import { fallbackRestaurants } from "@/data/restaurants";
interface AmapPoiV5 { interface AmapPoiV5 {
id: string; id: string;
@@ -95,9 +94,6 @@ function filterByPrice(
} }
export async function POST(req: Request) { export async function POST(req: Request) {
let restaurants: Restaurant[] = fallbackRestaurants;
let creatorId = "";
try { try {
const body = await req.json(); const body = await req.json();
const { const {
@@ -108,49 +104,61 @@ export async function POST(req: Request) {
cuisine = "不限", cuisine = "不限",
userId = "", userId = "",
} = body; } = body;
creatorId = userId;
if (lat && lng) { if (!lat || !lng) {
const apiKey = process.env.AMAP_API_KEY; return NextResponse.json(
if (!apiKey) { { error: "无法获取位置信息,请允许定位权限后重试" },
console.error("AMAP_API_KEY not configured"); { status: 400 },
} else { );
const url = new URL("https://restapi.amap.com/v5/place/around");
url.searchParams.set("key", apiKey);
url.searchParams.set("location", `${lng},${lat}`);
url.searchParams.set("radius", String(radius));
url.searchParams.set("types", "050000");
url.searchParams.set("show_fields", "business,photos");
url.searchParams.set("sortrule", "weight");
const needsPriceFilter = priceRange !== "any";
url.searchParams.set("page_size", needsPriceFilter ? "25" : "15");
if (cuisine && cuisine !== "不限") {
url.searchParams.set("keywords", cuisine);
}
const amapRes = await fetch(url.toString());
const amapData = await amapRes.json();
if (amapData.status === "1" && amapData.pois?.length > 0) {
let results: Restaurant[] = amapData.pois.map(mapPoiToRestaurant);
results = filterByPrice(results, priceRange);
restaurants = results.slice(0, 15);
}
}
} }
} catch (e) {
console.error("Amap API error, using fallback data:", e);
}
try { const apiKey = process.env.AMAP_API_KEY;
const roomId = await createRoom(restaurants, creatorId); if (!apiKey) {
console.error("AMAP_API_KEY not configured");
return NextResponse.json(
{ error: "服务配置异常,请稍后重试" },
{ status: 500 },
);
}
const url = new URL("https://restapi.amap.com/v5/place/around");
url.searchParams.set("key", apiKey);
url.searchParams.set("location", `${lng},${lat}`);
url.searchParams.set("radius", String(radius));
url.searchParams.set("types", "050000");
url.searchParams.set("show_fields", "business,photos");
url.searchParams.set("sortrule", "weight");
const needsPriceFilter = priceRange !== "any";
url.searchParams.set("page_size", needsPriceFilter ? "25" : "15");
if (cuisine && cuisine !== "不限") {
url.searchParams.set("keywords", cuisine);
}
const amapRes = await fetch(url.toString());
const amapData = await amapRes.json();
let restaurants: Restaurant[] = [];
if (amapData.status === "1" && amapData.pois?.length > 0) {
let results: Restaurant[] = amapData.pois.map(mapPoiToRestaurant);
results = filterByPrice(results, priceRange);
restaurants = results.slice(0, 15);
}
if (restaurants.length === 0) {
return NextResponse.json(
{ error: "附近没有找到餐厅,试试扩大搜索范围或换个菜系" },
{ status: 404 },
);
}
const roomId = await createRoom(restaurants, userId);
return NextResponse.json({ roomId, restaurants }); return NextResponse.json({ roomId, restaurants });
} catch (e) { } catch (e) {
console.error("Failed to create room:", e); console.error("Failed to create room:", e);
return NextResponse.json( return NextResponse.json(
{ error: "创建房间失败,请重试" }, { error: "搜索餐厅失败,请检查网络后重试" },
{ status: 500 }, { status: 500 },
); );
} }
+8 -7
View File
@@ -153,20 +153,21 @@ export default function LandingPage() {
body: JSON.stringify({ ...coords, radius, priceRange, cuisine, userId: getUserId() }), body: JSON.stringify({ ...coords, radius, priceRange, cuisine, userId: getUserId() }),
}); });
const data = await res.json();
if (!res.ok) { if (!res.ok) {
throw new Error("创建房间失败"); throw new Error(data.error || "创建房间失败");
} }
const { roomId } = await res.json(); if (!data.roomId) {
if (!roomId) {
throw new Error("创建房间失败"); throw new Error("创建房间失败");
} }
setLoadingText("正在进入房间..."); setLoadingText("正在进入房间...");
await joinRoom(roomId); await joinRoom(data.roomId);
router.push(`/room/${roomId}`); router.push(`/room/${data.roomId}`);
} catch { } catch (e) {
setError("创建失败,请重试"); setError(e instanceof Error ? e.message : "创建失败,请重试");
setLoading(false); setLoading(false);
setLoadingText(""); setLoadingText("");
} }