1
Fork 0
href-plus/source/ts/utilities/search.ts

65 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-02-09 15:04:34 +00:00
import {debug} from './debug.js';
2022-01-03 17:21:21 +00:00
type ApiSearchData = {
releases: Array<{
'artist-credit': Array<{
joinphrase?: string;
name: string;
}>;
disambiguation?: string;
id: string;
title: string;
}>;
};
export type SearchResult = {
artist: string;
disambiguation?: string;
id: string;
title: string;
};
2022-02-05 13:16:58 +00:00
export const searchLimit = 25;
2022-01-03 17:21:21 +00:00
export default async function searchReleases(
query: string,
offset?: number,
2022-01-03 17:21:21 +00:00
): Promise<SearchResult[]> {
query = encodeURIComponent(query);
2022-02-05 13:16:58 +00:00
let url = `https://musicbrainz.org/ws/2/release?query=${query}&limit=${searchLimit}`;
if (offset !== undefined) {
url += `&offset=${offset}`;
}
2022-01-03 17:21:21 +00:00
const response = await window.fetch(url, {
headers: {
accept: 'application/json',
2022-01-06 20:12:20 +00:00
'user-agent': hrefPlusUserAgent,
2022-01-03 17:21:21 +00:00
},
});
if (!response.ok) {
throw new Error(`Search API returned ${response.status}`);
}
const data = (await response.json()) as ApiSearchData;
2022-02-09 15:04:34 +00:00
debug(data);
2022-01-03 17:21:21 +00:00
const results: SearchResult[] = [];
for (const release of data.releases) {
const artist = release['artist-credit']
.map(({name, joinphrase}) => `${name}${joinphrase ?? ''}`)
.join('');
results.push({
artist,
disambiguation: release.disambiguation,
id: release.id,
title: release.title,
});
}
return results;
}