Auto update song on move

This commit is contained in:
Tamius Han 2025-12-09 22:20:24 +01:00
parent 8271b1e147
commit fec862e223

View File

@ -19,15 +19,35 @@ export async function lockSong(id: number, locked: boolean, res: any) {
export async function moveSong(id: number, position: number, res: any) {
try {
const result = await db.query(
`UPDATE songs SET position=$1 WHERE id=$2 RETURNING *`,
[position, id]
);
if (result.rowCount === 0) return res.status(404).json({ error: "Song not found" });
await db.query("BEGIN");
res.json({ song: result.rows[0] });
// Fetch the song
const songRes = await db.query(`SELECT * FROM songs WHERE id=$1`, [id]);
if (songRes.rowCount === 0) {
await db.query("ROLLBACK");
return res.status(404).json({ error: "Song not found" });
}
const song = songRes.rows[0];
// Update position
await db.query(`UPDATE songs SET position=$1 WHERE id=$2`, [position, id]);
// Auto-adjust status based on movement
if (song.status === 2) {
// Moved from played → queued
await db.query(`UPDATE songs SET status=0 WHERE id=$1`, [id]);
} else if (song.status === 0 && position === 0) {
// Optional: if moved to top, mark as playing
await db.query(`UPDATE songs SET status=1 WHERE id=$1`, [id]);
}
await db.query("COMMIT");
const updatedRes = await db.query(`SELECT * FROM songs WHERE id=$1`, [id]);
res.json({ song: updatedRes.rows[0] });
} catch (err) {
console.error(err);
await db.query("ROLLBACK");
console.error("Error moving song:", err);
res.status(500).json({ error: "Server error" });
}
}