2025-04-24 15:28:22 +02:00

57 lines
1.9 KiB
TypeScript

import { Song, Playlist } from '../types/interfaces';
const API_URL = 'http://localhost:3000/api';
async function handleResponse<T>(response: Response): Promise<T> {
if (!response.ok) {
const error = await response.json().catch(() => ({ message: 'An error occurred' }));
throw new Error(error.message || 'An error occurred');
}
return response.json();
}
export const api = {
async getSongs(): Promise<Song[]> {
console.log('Fetching songs from API...');
const response = await fetch(`${API_URL}/songs`);
const data = await handleResponse<Song[]>(response);
console.log(`Received ${data.length} songs from API`);
return data;
},
async saveSongs(songs: Song[]): Promise<Song[]> {
console.log(`Saving ${songs.length} songs to API...`);
const response = await fetch(`${API_URL}/songs/batch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(songs),
});
const data = await handleResponse<Song[]>(response);
console.log(`Successfully saved ${data.length} songs`);
return data;
},
async getPlaylists(): Promise<Playlist[]> {
console.log('Fetching playlists from API...');
const response = await fetch(`${API_URL}/playlists`);
const data = await handleResponse<Playlist[]>(response);
console.log(`Received ${data.length} playlists from API`);
return data;
},
async savePlaylists(playlists: Playlist[]): Promise<Playlist[]> {
console.log(`Saving ${playlists.length} playlists to API...`);
const response = await fetch(`${API_URL}/playlists/batch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(playlists),
});
const data = await handleResponse<Playlist[]>(response);
console.log(`Successfully saved ${data.length} playlists`);
return data;
},
};