First commit
This commit is contained in:
65
app/api/mahasiswa/statistik/route.ts
Normal file
65
app/api/mahasiswa/statistik/route.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import pool from '@/lib/db';
|
||||
import { RowDataPacket } from 'mysql2';
|
||||
|
||||
interface MahasiswaStatistik extends RowDataPacket {
|
||||
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() {
|
||||
const connection = await pool.getConnection();
|
||||
|
||||
try {
|
||||
// Query untuk mendapatkan statistik mahasiswa per tahun angkatan
|
||||
const [results] = await connection.query<MahasiswaStatistik[]>(`
|
||||
SELECT
|
||||
tahun_angkatan,
|
||||
COUNT(*) as total_mahasiswa,
|
||||
SUM(CASE WHEN jk = 'Pria' THEN 1 ELSE 0 END) as pria,
|
||||
SUM(CASE WHEN jk = 'Wanita' THEN 1 ELSE 0 END) as wanita
|
||||
FROM mahasiswa
|
||||
GROUP BY 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',
|
||||
},
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user