95 lines
2.7 KiB
TypeScript
95 lines
2.7 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import supabase from '@/lib/db';
|
|
|
|
interface MahasiswaStatistik {
|
|
tahun_angkatan: number;
|
|
total_mahasiswa: number;
|
|
pria: number;
|
|
wanita: number;
|
|
}
|
|
|
|
// Fungsi untuk menangani preflight request (OPTIONS)
|
|
export async function OPTIONS() {
|
|
return new NextResponse(null, {
|
|
status: 200,
|
|
headers: {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
'Access-Control-Max-Age': '86400', // 24 jam
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function GET() {
|
|
try {
|
|
// Get all mahasiswa data
|
|
const { data, error } = await supabase
|
|
.from('mahasiswa')
|
|
.select('tahun_angkatan, jk');
|
|
|
|
if (error) {
|
|
console.error('Error fetching mahasiswa statistik:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to fetch mahasiswa statistik' },
|
|
{
|
|
status: 500,
|
|
headers: {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
},
|
|
}
|
|
);
|
|
}
|
|
|
|
// Group by tahun_angkatan and calculate statistics
|
|
const groupedData = data.reduce((acc, item) => {
|
|
const tahun = item.tahun_angkatan;
|
|
if (!acc[tahun]) {
|
|
acc[tahun] = {
|
|
tahun_angkatan: tahun,
|
|
total_mahasiswa: 0,
|
|
pria: 0,
|
|
wanita: 0
|
|
};
|
|
}
|
|
|
|
acc[tahun].total_mahasiswa += 1;
|
|
if (item.jk === 'Pria') {
|
|
acc[tahun].pria += 1;
|
|
} else if (item.jk === 'Wanita') {
|
|
acc[tahun].wanita += 1;
|
|
}
|
|
|
|
return acc;
|
|
}, {} as Record<number, MahasiswaStatistik>);
|
|
|
|
// Convert to array and sort by tahun_angkatan
|
|
const results: MahasiswaStatistik[] = Object.values(groupedData)
|
|
.sort((a, b) => a.tahun_angkatan - b.tahun_angkatan);
|
|
|
|
// Menambahkan header cache dan CORS
|
|
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 mahasiswa statistik:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to fetch mahasiswa statistik' },
|
|
{
|
|
status: 500,
|
|
headers: {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
},
|
|
}
|
|
);
|
|
}
|
|
}
|