92 lines
2.3 KiB
TypeScript
92 lines
2.3 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { requireAuth } from '@/lib/auth'
|
|
|
|
export async function PUT(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const user = await requireAuth()
|
|
const { id } = await params
|
|
|
|
const playlist = await prisma.playlist.findUnique({
|
|
where: { id },
|
|
})
|
|
|
|
if (!playlist) {
|
|
return NextResponse.json({ error: 'Playlist not found' }, { status: 404 })
|
|
}
|
|
|
|
if (playlist.userId !== user.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 403 })
|
|
}
|
|
|
|
const body = await request.json()
|
|
const { songIds } = body
|
|
|
|
if (!Array.isArray(songIds) || songIds.length === 0) {
|
|
return NextResponse.json({ error: 'songIds array is required' }, { status: 400 })
|
|
}
|
|
|
|
// Update positions in a transaction
|
|
await prisma.$transaction(
|
|
songIds.map((songId: string, index: number) =>
|
|
prisma.playlistSong.update({
|
|
where: {
|
|
playlistId_songId: {
|
|
playlistId: id,
|
|
songId,
|
|
},
|
|
},
|
|
data: {
|
|
position: index,
|
|
},
|
|
})
|
|
)
|
|
)
|
|
|
|
const updatedPlaylist = await prisma.playlist.findUnique({
|
|
where: { id },
|
|
include: {
|
|
songs: {
|
|
include: {
|
|
song: {
|
|
include: {
|
|
artist: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
slug: true,
|
|
avatarUrl: true,
|
|
verified: true,
|
|
},
|
|
},
|
|
album: {
|
|
select: {
|
|
id: true,
|
|
title: true,
|
|
slug: true,
|
|
coverUrl: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
orderBy: {
|
|
position: 'asc',
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
return NextResponse.json(updatedPlaylist)
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message === 'Unauthorized') {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
console.error('Error reordering playlist:', error)
|
|
return NextResponse.json({ error: 'Failed to reorder playlist' }, { status: 500 })
|
|
}
|
|
}
|