route.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { restApiFetch } from "@/utils/bagisto";
  3. import { isBagistoError } from "@/utils/type-guards";
  4. import { getAuthToken } from "@/utils/helper";
  5. export async function GET(req: NextRequest) {
  6. try {
  7. const guestToken = getAuthToken(req);
  8. // 👇 取出所有前端传过来的查询参数
  9. const searchParams = req.nextUrl.searchParams;
  10. const page = searchParams.get("page");
  11. const per_page = searchParams.get("per_page");
  12. const amountType = searchParams.get("amountType");
  13. // 👇 构建查询参数数组(自动过滤空值)
  14. const queryParts: string[] = [];
  15. if (page) queryParts.push(`page=${page}`);
  16. if (per_page) queryParts.push(`per_page=${per_page}`);
  17. if (amountType) queryParts.push(`amountType=${amountType}`);
  18. // 👇 最终拼接 URL
  19. let apiUrl = "/customer/reward-points/history";
  20. if (queryParts.length > 0) {
  21. apiUrl += "?" + queryParts.join("&");
  22. }
  23. console.log("最终请求API地址:", apiUrl);
  24. const response = await restApiFetch<any>({
  25. api: apiUrl,
  26. method: "GET",
  27. cache: "no-store",
  28. guestToken,
  29. });
  30. return NextResponse.json({
  31. status: response.status,
  32. data: response.body,
  33. });
  34. } catch (error) {
  35. if (isBagistoError(error)) {
  36. return NextResponse.json(
  37. {
  38. data: null,
  39. error: error.cause ?? error,
  40. },
  41. { status: 200 }
  42. );
  43. }
  44. return NextResponse.json(
  45. {
  46. message: "Network error",
  47. error: error instanceof Error ? error.message : error,
  48. },
  49. { status: 500 }
  50. );
  51. }
  52. }