68 lines
2.2 KiB
TypeScript

import express from 'express';
import { Playlist } from '../models/Playlist.js';
import { Request, Response } from 'express';
const router = express.Router();
// Get all playlists
router.get('/', async (req: Request, res: Response) => {
try {
const playlists = await Playlist.find({});
res.json(playlists);
} catch (error) {
console.error('Error fetching playlists:', error);
res.status(500).json({ message: 'Error fetching playlists', error });
}
});
// Get playlist structure only (without track data) for faster loading
router.get('/structure', async (req: Request, res: Response) => {
try {
const playlists = await Playlist.find({});
// Remove track data from playlists to reduce payload size
const structureOnly = playlists.map(playlist => {
const cleanPlaylist = playlist.toObject() as any;
// Remove tracks from the main playlist
delete cleanPlaylist.tracks;
// Recursively remove tracks from children
const cleanChildren = (children: any[]): any[] => {
return children.map(child => {
const cleanChild = { ...child } as any;
delete cleanChild.tracks;
if (cleanChild.children && cleanChild.children.length > 0) {
cleanChild.children = cleanChildren(cleanChild.children);
}
return cleanChild;
});
};
if (cleanPlaylist.children && cleanPlaylist.children.length > 0) {
cleanPlaylist.children = cleanChildren(cleanPlaylist.children);
}
return cleanPlaylist;
});
res.json(structureOnly);
} catch (error) {
console.error('Error fetching playlist structure:', error);
res.status(500).json({ message: 'Error fetching playlist structure', error });
}
});
// Save playlists in batch (replacing all existing ones)
router.post('/batch', async (req, res) => {
try {
await Playlist.deleteMany({}); // Clear existing playlists
const playlists = await Playlist.create(req.body);
res.json(playlists);
} catch (error) {
console.error('Error saving playlists:', error);
res.status(500).json({ error: 'Failed to save playlists' });
}
});
export const playlistsRouter = router;