49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import sql from '@/lib/db'
|
|
import { slugify } from '@/lib/utils'
|
|
|
|
// GET /api/apps
|
|
export async function GET() {
|
|
const session = await getServerSession(authOptions)
|
|
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const apps = await sql`SELECT * FROM apps ORDER BY created_at DESC`
|
|
return NextResponse.json(apps)
|
|
}
|
|
|
|
// POST /api/apps
|
|
export async function POST(req: NextRequest) {
|
|
const session = await getServerSession(authOptions)
|
|
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const body = await req.json()
|
|
const { name, description, icon_url } = body
|
|
const slug = body.slug ?? slugify(name)
|
|
|
|
if (!name || !slug) {
|
|
return NextResponse.json({ error: 'name and slug are required' }, { status: 400 })
|
|
}
|
|
|
|
try {
|
|
const [app] = await sql`
|
|
INSERT INTO apps (name, slug, description, icon_url)
|
|
VALUES (${name}, ${slug}, ${description ?? null}, ${icon_url ?? null})
|
|
RETURNING *
|
|
`
|
|
|
|
await sql`
|
|
INSERT INTO audit_logs (app_id, action, actor)
|
|
VALUES (${app.id}, 'create_app', ${session.user?.name ?? 'admin'})
|
|
`
|
|
|
|
return NextResponse.json(app, { status: 201 })
|
|
} catch (err: any) {
|
|
if (err.code === '23505') {
|
|
return NextResponse.json({ error: 'Slug already exists.' }, { status: 409 })
|
|
}
|
|
return NextResponse.json({ error: err.message }, { status: 500 })
|
|
}
|
|
}
|