Files
config-vault/app/api/apps/[id]/config/route.ts
T
2026-08-26 14:21:53 +03:00

57 lines
2.0 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import sql from '@/lib/db'
// GET /api/apps/[id]/config?env=production
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { id } = await params
const env = req.nextUrl.searchParams.get('env') ?? 'production'
const entries = await sql`
SELECT ce.*
FROM config_entries ce
JOIN environments e ON e.id = ce.environment_id
WHERE e.app_id = ${id} AND e.name = ${env}
ORDER BY ce.key
`
return NextResponse.json(entries)
}
// POST /api/apps/[id]/config
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const session = await getServerSession(authOptions)
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { id } = await params
const body = await req.json()
const { environment_id, key, value, type, description, environment } = body
if (!environment_id || !key || value === undefined) {
return NextResponse.json({ error: 'environment_id, key, value are required' }, { status: 400 })
}
try {
const [entry] = await sql`
INSERT INTO config_entries (environment_id, key, value, type, description)
VALUES (${environment_id}, ${key.toUpperCase()}, ${value}, ${type ?? 'text'}, ${description ?? null})
RETURNING *
`
await sql`
INSERT INTO audit_logs (app_id, environment, action, key, actor)
VALUES (${id}, ${environment}, 'create', ${key}, ${session.user?.name ?? 'admin'})
`
return NextResponse.json(entry, { status: 201 })
} catch (err: any) {
if (err.code === '23505') {
return NextResponse.json({ error: `Key "${key}" already exists in this environment` }, { status: 409 })
}
return NextResponse.json({ error: err.message }, { status: 500 })
}
}