Skip to content

Instantly share code, notes, and snippets.

@lenkan
Created September 19, 2020 13:18
Show Gist options
  • Save lenkan/5a917f2511fad61a2b99f509305fafd1 to your computer and use it in GitHub Desktop.
Save lenkan/5a917f2511fad61a2b99f509305fafd1 to your computer and use it in GitHub Desktop.
Musicbrainz client
async function fetchJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`GET ${url} ${response.status} - ${response.statusText} `,
);
}
return response.json();
}
function mapReleaseGroups(groups) {
return groups.map((group) => {
return {
id: group.id,
title: group.title,
};
});
}
function findWikidataResource(relations) {
let wikiRelation = relations.find((rel) => rel.type === "wikidata");
return wikiRelation?.url?.resource;
}
export async function getArtist(id) {
if (!id) {
throw Error("No id specified");
}
const url = new URL(`http://musicbrainz.org/ws/2/artist/${id}`);
url.searchParams.set("fmt", "json");
url.searchParams.set("inc", "url-rels+release-groups");
const data = await fetchJson(url);
return {
name: data.name,
albums: mapReleaseGroups(data["release-groups"]),
wikidataKey: findWikidataResource(data.relations),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment