83 lines
2.4 KiB
TypeScript
83 lines
2.4 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import supabase from '@/lib/db';
|
|
|
|
interface AsalDaerah {
|
|
kabupaten: string;
|
|
jumlah: number;
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
const { searchParams } = new URL(request.url);
|
|
const tahunAngkatan = searchParams.get('tahun_angkatan');
|
|
|
|
if (!tahunAngkatan) {
|
|
return NextResponse.json(
|
|
{ error: 'Tahun angkatan diperlukan' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
try {
|
|
const { data, error } = await supabase
|
|
.from('mahasiswa')
|
|
.select('kabupaten')
|
|
.eq('tahun_angkatan', parseInt(tahunAngkatan));
|
|
|
|
if (error) {
|
|
console.error('Error fetching asal daerah per angkatan:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to fetch asal daerah data' },
|
|
{
|
|
status: 500,
|
|
headers: {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
},
|
|
}
|
|
);
|
|
}
|
|
|
|
// Group by kabupaten and count
|
|
const groupedData = data.reduce((acc, item) => {
|
|
acc[item.kabupaten] = (acc[item.kabupaten] || 0) + 1;
|
|
return acc;
|
|
}, {} as Record<string, number>);
|
|
|
|
// Convert to final format and sort
|
|
const results: AsalDaerah[] = Object.entries(groupedData)
|
|
.map(([kabupaten, jumlah]) => ({
|
|
kabupaten,
|
|
jumlah
|
|
}))
|
|
.sort((a, b) => {
|
|
// Sort by jumlah DESC, then by kabupaten ASC
|
|
if (a.jumlah !== b.jumlah) {
|
|
return b.jumlah - a.jumlah;
|
|
}
|
|
return a.kabupaten.localeCompare(b.kabupaten);
|
|
});
|
|
|
|
return NextResponse.json(results, {
|
|
headers: {
|
|
'Cache-Control': 'public, max-age=60, stale-while-revalidate=30',
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Error fetching asal daerah per angkatan:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to fetch asal daerah data' },
|
|
{
|
|
status: 500,
|
|
headers: {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
},
|
|
}
|
|
);
|
|
}
|
|
}
|