Files
InaTrading-Portal/src/app/api/locations/all/route.ts
2026-04-24 05:19:05 +07:00

44 lines
1.3 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { API_URL, makeHeaders } from "@/lib/api";
export async function GET(req: NextRequest) {
const token = req.headers.get("x-auth-token") || "";
const headers = makeHeaders(token ? `Bearer ${token}` : undefined);
// 1. Fetch semua provinsi
const provincesRes = await fetch(`${API_URL}/api/v1.0/provinces`, {
method: "GET",
headers,
cache: "no-store",
});
const provincesData = await provincesRes.json().catch(() => ({}));
if (!provincesRes.ok) {
return NextResponse.json(provincesData, { status: provincesRes.status });
}
const provinces: { id: string; name: string }[] = Array.isArray(provincesData?.rows)
? provincesData.rows
: [];
// 2. Fetch semua kota secara paralel
const cityResults = await Promise.all(
provinces.map(async (province) => {
const res = await fetch(
`${API_URL}/api/v1.0/cities?provinceId=${province.id}`,
{ method: "GET", headers, cache: "no-store" }
);
const data = await res.json().catch(() => ({}));
const rows: { id: string; name: string }[] = Array.isArray(data?.rows)
? data.rows
: [];
return rows.map((city) => ({ ...city, provinceId: province.id }));
})
);
const cities = cityResults.flat();
return NextResponse.json({ provinces, cities });
}