64 lines
2.3 KiB
TypeScript
64 lines
2.3 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { getCurrentUser } from '@/lib/auth'
|
|
|
|
export async function GET() {
|
|
try {
|
|
const user = await getCurrentUser()
|
|
if (!user) return NextResponse.json({ error: 'Non authentifié' }, { status: 401 })
|
|
|
|
const servers: any[] = await prisma.$queryRawUnsafe(`
|
|
SELECT s.*,
|
|
(SELECT json_build_object(
|
|
'cpuUsage', sm."cpuUsage",
|
|
'ramUsage', sm."ramUsage",
|
|
'diskUsage', sm."diskUsage",
|
|
'uptime', sm.uptime,
|
|
'timestamp', sm."timestamp"
|
|
) FROM "ServerMetric" sm
|
|
WHERE sm."serverId" = s.id
|
|
ORDER BY sm."timestamp" DESC LIMIT 1) as latest_metric
|
|
FROM "Server" s
|
|
WHERE s."userId" = $1
|
|
ORDER BY s.name ASC
|
|
`, user.id)
|
|
|
|
const parsed = servers.map((s: any) => ({
|
|
...s,
|
|
latest_metric: s.latest_metric || null,
|
|
}))
|
|
|
|
return NextResponse.json(parsed)
|
|
} catch (error) {
|
|
console.error(error)
|
|
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const user = await getCurrentUser()
|
|
if (!user) return NextResponse.json({ error: 'Non authentifié' }, { status: 401 })
|
|
|
|
const body = await request.json()
|
|
const id = `${Date.now().toString(36)}-${Math.random().toString(36).substr(2, 9)}`
|
|
const now = new Date()
|
|
|
|
const { name, ip, os, cpu, ram, disk, startDate, endDate, monthlyCost, status, notes } = body
|
|
|
|
await prisma.$executeRawUnsafe(`
|
|
INSERT INTO "Server" (id, "userId", name, ip, os, cpu, ram, disk, "startDate", "endDate", "monthlyCost", status, notes, "createdAt", "updatedAt")
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
|
`, id, user.id, name || '', ip || '', os || '', cpu || '', ram || '', disk || '',
|
|
startDate ? new Date(startDate) : null, endDate ? new Date(endDate) : null,
|
|
monthlyCost ? Number(monthlyCost) : 0, status || 'ACTIVE', notes || '', now, now)
|
|
|
|
const created: any[] = await prisma.$queryRawUnsafe(`SELECT * FROM "Server" WHERE id = $1`, id)
|
|
|
|
return NextResponse.json(created[0])
|
|
} catch (error) {
|
|
console.error(error)
|
|
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
|
|
}
|
|
}
|