Files
hoerdle/app/api/songs/route.ts
2025-11-21 12:25:19 +01:00

94 lines
2.8 KiB
TypeScript

import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { writeFile } from 'fs/promises';
import path from 'path';
import { parseBuffer } from 'music-metadata';
const prisma = new PrismaClient();
export async function GET() {
const songs = await prisma.song.findMany({
orderBy: { createdAt: 'desc' },
select: {
id: true,
title: true,
artist: true,
filename: true,
createdAt: true,
}
});
return NextResponse.json(songs);
}
export async function POST(request: Request) {
try {
const formData = await request.formData();
const file = formData.get('file') as File;
let title = formData.get('title') as string;
let artist = formData.get('artist') as string;
if (!file) {
return NextResponse.json({ error: 'No file provided' }, { status: 400 });
}
const buffer = Buffer.from(await file.arrayBuffer());
// Try to extract metadata if title or artist are missing
if (!title || !artist) {
try {
const metadata = await parseBuffer(buffer, file.type);
if (!title && metadata.common.title) {
title = metadata.common.title;
}
if (!artist && metadata.common.artist) {
artist = metadata.common.artist;
}
} catch (e) {
console.error('Failed to parse metadata:', e);
}
}
// Fallback if still missing
if (!title) title = 'Unknown Title';
if (!artist) artist = 'Unknown Artist';
const filename = `${Date.now()}-${file.name.replace(/[^a-zA-Z0-9.]/g, '_')}`;
const uploadDir = path.join(process.cwd(), 'public/uploads');
await writeFile(path.join(uploadDir, filename), buffer);
const song = await prisma.song.create({
data: {
title,
artist,
filename,
},
});
return NextResponse.json(song);
} catch (error) {
console.error('Error uploading song:', error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}
export async function PUT(request: Request) {
try {
const { id, title, artist } = await request.json();
if (!id || !title || !artist) {
return NextResponse.json({ error: 'Missing fields' }, { status: 400 });
}
const updatedSong = await prisma.song.update({
where: { id: Number(id) },
data: { title, artist },
});
return NextResponse.json(updatedSong);
} catch (error) {
console.error('Error updating song:', error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}