import { fetchJSON } from "https://esm.town/v/axelav/fetchJSON";
import process from "node:process";
export async function discogs(
request: express.Request,
response: express.Response
) {
console.log("Request!", request);
interface Artist {
name: string;
join: string;
}
interface RecordLabel {
name: string;
}
interface DiscogsRelease {
artists: Artist[];
title: string;
year: number;
genres: string[];
styles: string[];
labels: RecordLabel[];
master_id?: string;
main_release?: string;
uri: string;
id: string;
}
const token = process.env.DISCOGS_API_TOKEN;
const toLowerCaseAndSort = (list: string[]) =>
list.map((t) => t.toLowerCase()).sort();
const unique = (x: string, idx: number, self: string[]) =>
self.indexOf(x) === idx;
const getLabel = (list: RecordLabel[]) => {
const noLabelText = "Not On Label";
if (!list || !list.length) {
return noLabelText;
}
const first = list[0]?.name;
if (first.match(noLabelText)) {
return noLabelText;
}
return first.trim().replace(/\s\(\d+\)/g, "");
};
const addSpaceAfterJoin = (artist: Artist) => {
const join = artist.join;
if (join) {
return join.replace(/(\/)/g, "$1 ");
}
return "";
};
const formatArtist = (artist: Artist) => {
const name = artist.name.trim().replace(/\s\(\d+\)/g, "");
const join = addSpaceAfterJoin(artist);
return `${name}${join}`;
};
const formatRelease = (release: DiscogsRelease) => {
const {
artists = [],
title,
year,
genres = [],
styles = [],
labels = [],
} = release;
return {
artist: artists.reduce((acc, x) => `${acc}${formatArtist(x)}`, ""),
title,
year,
label: getLabel(labels),
tags: [
...toLowerCaseAndSort(genres),
...toLowerCaseAndSort(styles),
].filter(unique),
url: release.uri,
};
};
const getSearchResults = async (
query: string,
isMaster = true
): Promise<{
results: DiscogsRelease[];
}> =>
fetchJSON(
`https://api.discogs.com/database/search?token=${token}&q=${query}${
isMaster ? "&type=master" : ""
}`
);
const getMasterRelease = async (id: string): Promise<DiscogsRelease> =>
fetchJSON(
`https://api.discogs.com/masters/${id}?token=${token}`
);
const getMainRelease = async (id: string): Promise<DiscogsRelease> =>
fetchJSON(
`https://api.discogs.com/releases/${id}?token=${token}`
);
const params = request.params;