-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-vinyls.js
74 lines (61 loc) · 2.25 KB
/
get-vinyls.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require('dotenv').config();
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const fs = require('fs');
const username = 'lokta';
const apiUrl = `https://api.discogs.com/users/${username}/collection/folders/0/releases?per_page=100`;
const fetchVinyls = async () => {
try {
const response = await fetch(apiUrl, {
headers: {
'Authorization': `Discogs token=${process.env.DISCOGS_TOKEN}`
}
});
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
const data = await response.json();
return data.releases;
} catch (error) {
console.error('Error fetching data from Discogs:', error);
return [];
}
};
const fetchImage = async (url) => {
const imagePath = `vinyls-cover/${url.split('/').pop()}`;
const imagePathInAssets = `assets/${imagePath}`;
if (fs.existsSync(imagePathInAssets)) {
return imagePath;
}
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
const buffer = await response.arrayBuffer();
fs.writeFileSync(imagePathInAssets, Buffer.from(buffer));
return imagePath;
} catch (error) {
console.error('Error fetching image:', error);
return null;
}
};
const transformToJSON = (vinyls) => {
return vinyls.map(vinyl => ({
title: vinyl.basic_information.title,
artist: vinyl.basic_information.artists.map(artist => artist.name).join(", "),
label: vinyl.basic_information.labels.map(label => label.name).join(", "),
year: vinyl.basic_information.year,
image: vinyl.basic_information.cover_image
}));
};
const main = async () => {
const vinyls = await fetchVinyls();
for (const vinyl of vinyls) {
const imagePath = await fetchImage(vinyl.basic_information.cover_image);
vinyl.basic_information.cover_image = imagePath;
}
const vinylsJSON = transformToJSON(vinyls);
fs.writeFileSync('data/vinyls.json', JSON.stringify(vinylsJSON, null, 4));
console.log('Vinyls data written to vinyls.json');
};
main();