93 lines
2.7 KiB
TypeScript
93 lines
2.7 KiB
TypeScript
// =====================================================
|
|
// 資料庫狀態監控 API
|
|
// =====================================================
|
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { db } from '@/lib/database';
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
// 獲取備援狀態
|
|
const failoverStatus = db.getFailoverStatus();
|
|
|
|
if (!failoverStatus) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
message: '備援功能未啟用',
|
|
data: null
|
|
});
|
|
}
|
|
|
|
// 獲取詳細狀態信息
|
|
const status = {
|
|
isEnabled: failoverStatus.isEnabled,
|
|
currentDatabase: failoverStatus.currentDatabase,
|
|
masterHealthy: failoverStatus.masterHealthy,
|
|
slaveHealthy: failoverStatus.slaveHealthy,
|
|
lastHealthCheck: failoverStatus.lastHealthCheck && failoverStatus.lastHealthCheck > 0
|
|
? new Date(failoverStatus.lastHealthCheck).toISOString()
|
|
: new Date().toISOString(), // 如果沒有健康檢查記錄,使用當前時間
|
|
consecutiveFailures: failoverStatus.consecutiveFailures,
|
|
uptime: process.uptime(),
|
|
timestamp: new Date().toISOString()
|
|
};
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: '資料庫狀態獲取成功',
|
|
data: status
|
|
});
|
|
|
|
} catch (error) {
|
|
console.error('獲取資料庫狀態失敗:', error);
|
|
return NextResponse.json({
|
|
success: false,
|
|
message: '獲取資料庫狀態失敗',
|
|
error: error instanceof Error ? error.message : '未知錯誤'
|
|
}, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
const { action, database } = body;
|
|
|
|
if (action === 'switch') {
|
|
if (!database || !['master', 'slave'].includes(database)) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
message: '無效的資料庫參數'
|
|
}, { status: 400 });
|
|
}
|
|
|
|
const success = await db.switchDatabase(database as 'master' | 'slave');
|
|
|
|
if (success) {
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: `已切換到 ${database} 資料庫`
|
|
});
|
|
} else {
|
|
return NextResponse.json({
|
|
success: false,
|
|
message: `切換到 ${database} 資料庫失敗`
|
|
}, { status: 400 });
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: false,
|
|
message: '無效的操作'
|
|
}, { status: 400 });
|
|
|
|
} catch (error) {
|
|
console.error('執行資料庫操作失敗:', error);
|
|
return NextResponse.json({
|
|
success: false,
|
|
message: '執行資料庫操作失敗',
|
|
error: error instanceof Error ? error.message : '未知錯誤'
|
|
}, { status: 500 });
|
|
}
|
|
}
|