// ===================================================== // 連線監控 API // ===================================================== import { NextRequest, NextResponse } from 'next/server'; import { smartPool } from '@/lib/smart-connection-pool'; export async function GET(request: NextRequest) { try { const { searchParams } = new URL(request.url); const action = searchParams.get('action') || 'stats'; switch (action) { case 'stats': // 獲取連線統計 const stats = smartPool.getConnectionStats(); return NextResponse.json({ success: true, message: '連線統計獲取成功', data: stats }); case 'cleanup': // 強制清理連線 console.log('🧹 執行強制連線清理...'); smartPool.forceCleanup(); const newStats = smartPool.getConnectionStats(); return NextResponse.json({ success: true, message: '連線清理完成', data: newStats }); case 'test': // 測試智能連線 try { const testResult = await smartPool.executeQueryOne( 'SELECT 1 as test_value', [], { userId: 'test', sessionId: 'test-session', requestId: 'test-request' } ); return NextResponse.json({ success: true, message: '智能連線測試成功', data: { testResult, stats: smartPool.getConnectionStats() } }); } catch (error) { return NextResponse.json({ success: false, error: '智能連線測試失敗', details: error instanceof Error ? error.message : '未知錯誤' }, { status: 500 }); } default: return NextResponse.json({ success: false, error: '無效的操作參數', availableActions: ['stats', 'cleanup', 'test'] }, { status: 400 }); } } catch (error) { console.error('❌ 連線監控 API 錯誤:', error); return NextResponse.json({ success: false, error: 'API 請求失敗', details: error instanceof Error ? error.message : '未知錯誤' }, { status: 500 }); } } export async function POST(request: NextRequest) { try { const body = await request.json(); const { action, maxIdleTime, maxConnectionAge } = body; switch (action) { case 'config': // 更新清理配置 smartPool.setCleanupParams(maxIdleTime, maxConnectionAge); return NextResponse.json({ success: true, message: '清理配置更新成功', data: { maxIdleTime: maxIdleTime || '未變更', maxConnectionAge: maxConnectionAge || '未變更' } }); case 'cleanup': // 強制清理連線 console.log('🧹 執行強制連線清理...'); smartPool.forceCleanup(); const stats = smartPool.getConnectionStats(); return NextResponse.json({ success: true, message: '連線清理完成', data: stats }); default: return NextResponse.json({ success: false, error: '無效的操作參數', availableActions: ['config', 'cleanup'] }, { status: 400 }); } } catch (error) { console.error('❌ 連線監控 POST API 錯誤:', error); return NextResponse.json({ success: false, error: 'API 請求失敗', details: error instanceof Error ? error.message : '未知錯誤' }, { status: 500 }); } }