-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed.js
65 lines (53 loc) · 1.93 KB
/
seed.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
require('dotenv').config();
const SpotifyWebApi = require('node-spotify-api');
const { MongoClient } = require('mongodb');
topGenres = ['pop', 'hip-hop', 'rock', 'country', 'r&b', 'folk']; ; // Manually specify the top genres as Spotify API doesn't provide a direct endpoint
const spotifyApi = new SpotifyWebApi({
id: process.env.SPOTIFY_CLIENT_ID,
secret: process.env.SPOTIFY_CLIENT_SECRET,
});
async function getTopArtists(genre) {
try {
const data = await spotifyApi.search({type: 'artist', query: `genre:"${genre}"`, limit: 50 });
return data.artists.items;
} catch (error) {
console.error(`Error getting artists for genre: ${genre}`, error);
return [];
}
}
async function getTopTracks(artistId) {
try {
const data = await spotifyApi.request(`https://api.spotify.com/v1/artists/${artistId}/top-tracks?market=us`);
return data.tracks;
} catch (error) {
console.error(`Error getting top tracks for artist: ${artistId}`, error);
return [];
}
}
async function main() {
const mongoClient = new MongoClient(process.env.MONGODB_URI);
await mongoClient.connect();
const db = mongoClient.db(process.env.MONGODB_DB);
// wipe the tracks collection
const trackList = await db.collections({name: 'tracks'})
if (trackList.length > 0) {
await db.collection('tracks').drop();
}
console.log('Getting top artists for the following genres: ' + topGenres.join(', '));
for (const genre of topGenres) {
const topArtists = await getTopArtists(genre);
console.log('Getting top tracks for each artist in the genre: ' + genre);
for (const artist of topArtists) {
const topTracks = await getTopTracks(artist.id);
for (const track of topTracks) {
process.stdout.write(".");
if (track.preview_url) {
const collection = db.collection('tracks');
await collection.insertOne(track);
}
}
}
}
mongoClient.close();
}
main();