blob: 5ae0d83144a2fe73c2deb56cb5588d97240b7a83 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import { Song } from "../types/song";
let cachedSongs: Song[] | null = null;
function fuzzyMatch(input: string): string {
return input.toLowerCase().replace(/[^0-9a-z ]/gi, '');
}
export async function fetchSongs(useCache=true): Promise<Song[]> {
if (useCache && cachedSongs) {
return cachedSongs;
}
try {
const response = await fetch('/songs');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const songsData: Song[] = await response.json();
cachedSongs = songsData;
return songsData;
} catch (error) {
console.error("Failed to fetch songs:", error);
throw error;
}
}
export async function searchSongs(searchTerm: string): Promise<Song[]> {
const songsToSearch = await fetchSongs();
const processedSearchTerm = fuzzyMatch(searchTerm);
const matchingSongs = songsToSearch
.filter((song: Song) => {
const songName = fuzzyMatch(song.name);
const songArtist = fuzzyMatch(song.artist);
if (songArtist.includes(processedSearchTerm) || songName.includes(processedSearchTerm)) {
return true;
}
return false;
})
.sort((a, b) =>
a.artist.toLowerCase().localeCompare(b.artist.toLocaleLowerCase())
|| a.name.toLowerCase().localeCompare(b.name.toLocaleLowerCase())
);
return matchingSongs;
}
export function getCachedSongs(): Song[] | null {
return cachedSongs;
}
|