playlist-manager.ts•1.73 kB
export interface Playlist {
id: string;
name: string;
description?: string;
songIds: string[];
createdAt: string;
updatedAt: string;
}
export class PlaylistManager {
private playlists: Map<string, Playlist> = new Map();
private nextId = 1;
async createPlaylist(name: string, description?: string): Promise<Playlist> {
const id = this.nextId.toString();
this.nextId++;
const playlist: Playlist = {
id,
name,
description,
songIds: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
this.playlists.set(id, playlist);
return playlist;
}
async getPlaylist(id: string): Promise<Playlist | undefined> {
return this.playlists.get(id);
}
async getAllPlaylists(): Promise<Playlist[]> {
return Array.from(this.playlists.values());
}
async addSongToPlaylist(playlistId: string, songId: string): Promise<void> {
const playlist = this.playlists.get(playlistId);
if (!playlist) {
throw new Error(`播放列表 ${playlistId} 不存在`);
}
if (!playlist.songIds.includes(songId)) {
playlist.songIds.push(songId);
playlist.updatedAt = new Date().toISOString();
}
}
async removeSongFromPlaylist(playlistId: string, songId: string): Promise<void> {
const playlist = this.playlists.get(playlistId);
if (!playlist) {
throw new Error(`播放列表 ${playlistId} 不存在`);
}
const index = playlist.songIds.indexOf(songId);
if (index > -1) {
playlist.songIds.splice(index, 1);
playlist.updatedAt = new Date().toISOString();
}
}
async deletePlaylist(id: string): Promise<boolean> {
return this.playlists.delete(id);
}
}