修正優化用戶管理功能

This commit is contained in:
2025-08-05 11:43:28 +08:00
parent 4e7b95d9fe
commit 65e9c411bf
2 changed files with 132 additions and 22 deletions

View File

@@ -1,32 +1,48 @@
import { NextRequest, NextResponse } from 'next/server';
import { requireAdmin } from '@/lib/auth';
import { verifyToken } from '@/lib/auth';
import { db } from '@/lib/database';
export async function GET(request: NextRequest) {
try {
await requireAdmin(request);
// 基本用戶統計
const total = await db.queryOne<{ count: number }>('SELECT COUNT(*) as count FROM users');
const admin = await db.queryOne<{ count: number }>("SELECT COUNT(*) as count FROM users WHERE role = 'admin'");
const developer = await db.queryOne<{ count: number }>("SELECT COUNT(*) as count FROM users WHERE role = 'developer'");
const user = await db.queryOne<{ count: number }>("SELECT COUNT(*) as count FROM users WHERE role = 'user'");
const today = await db.queryOne<{ count: number }>("SELECT COUNT(*) as count FROM users WHERE join_date = CURDATE()");
// 應用和評價統計
const totalApps = await db.queryOne<{ count: number }>('SELECT COUNT(*) as count FROM apps');
const totalReviews = await db.queryOne<{ count: number }>('SELECT COUNT(*) as count FROM judge_scores');
// 驗證管理員權限
const token = request.headers.get('authorization')?.replace('Bearer ', '')
if (!token) {
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
}
const decoded = verifyToken(token)
if (!decoded || decoded.role !== 'admin') {
return NextResponse.json({ error: 'Admin access required' }, { status: 403 })
}
// 優化:使用單一查詢獲取所有統計數據,減少資料庫查詢次數
const stats = await db.queryOne(`
SELECT
COUNT(*) as total,
COUNT(CASE WHEN role = 'admin' THEN 1 END) as admin,
COUNT(CASE WHEN role = 'developer' THEN 1 END) as developer,
COUNT(CASE WHEN role = 'user' THEN 1 END) as user,
COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN 1 END) as today
FROM users
`);
// 優化:並行查詢應用和評價統計
const [appsResult, reviewsResult] = await Promise.all([
db.queryOne('SELECT COUNT(*) as count FROM apps'),
db.queryOne('SELECT COUNT(*) as count FROM judge_scores')
]);
return NextResponse.json({
total: total?.count || 0,
admin: admin?.count || 0,
developer: developer?.count || 0,
user: user?.count || 0,
today: today?.count || 0,
totalApps: totalApps?.count || 0,
totalReviews: totalReviews?.count || 0
total: stats?.total || 0,
admin: stats?.admin || 0,
developer: stats?.developer || 0,
user: stats?.user || 0,
today: stats?.today || 0,
totalApps: appsResult?.count || 0,
totalReviews: reviewsResult?.count || 0
});
} catch (error) {
return NextResponse.json({ error: '內部伺服器錯誤', details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 });
console.error('Error fetching user stats:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}