This repository has been archived on 2026-06-15. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MediaLore/src/app/api/libraries/route.ts
2026-04-19 20:25:06 -04:00

54 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getLibraries, addLibrary } from '@/lib/libraries'
import { getLibrariesForUser } from '@/lib/users'
import { requireAuth, requireAdmin } from '@/lib/auth'
import type { LibraryType } from '@/types'
export async function GET(request: NextRequest) {
const auth = await requireAuth(request)
if (auth instanceof NextResponse) return auth
const { session } = auth
try {
const libraries =
session.role === 'admin'
? getLibraries().map((l) => ({ ...l, accessLevel: 'admin' }))
: getLibrariesForUser(session.userId, session.role)
return NextResponse.json(libraries)
} catch (err) {
console.error('Failed to read libraries', err)
return NextResponse.json({ error: 'Failed to load libraries' }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
const auth = await requireAdmin(request)
if (auth instanceof NextResponse) return auth
let body: { name?: string; path?: string; type?: string }
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
}
const { name, path, type } = body
if (!name || !path || !type) {
return NextResponse.json({ error: 'name, path, and type are required' }, { status: 400 })
}
const validTypes: LibraryType[] = ['comics', 'games', 'mixed', 'movies', 'tv']
if (!validTypes.includes(type as LibraryType)) {
return NextResponse.json({ error: `type must be one of: ${validTypes.join(', ')}` }, { status: 400 })
}
try {
const library = addLibrary(name, path, type as LibraryType)
return NextResponse.json(library, { status: 201 })
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to add library'
return NextResponse.json({ error: message }, { status: 400 })
}
}