forked from awicks44/JavaScript-SpotifyAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
266 lines (214 loc) · 8.47 KB
/
app.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
const APIController = (function() {
const clientId = 'ADD YOUR CLIENT ID';
const clientSecret = 'ADD YOUR CLIENT SECRET';
// private methods
const _getToken = async () => {
const result = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Authorization' : 'Basic ' + btoa(clientId + ':' + clientSecret)
},
body: 'grant_type=client_credentials'
});
const data = await result.json();
return data.access_token;
}
const _getGenres = async (token) => {
const result = await fetch(`https://api.spotify.com/v1/browse/categories?locale=sv_US`, {
method: 'GET',
headers: { 'Authorization' : 'Bearer ' + token}
});
const data = await result.json();
return data.categories.items;
}
const _getPlaylistByGenre = async (token, genreId) => {
const limit = 10;
const result = await fetch(`https://api.spotify.com/v1/browse/categories/${genreId}/playlists?limit=${limit}`, {
method: 'GET',
headers: { 'Authorization' : 'Bearer ' + token}
});
const data = await result.json();
return data.playlists.items;
}
const _getTracks = async (token, tracksEndPoint) => {
const limit = 10;
const result = await fetch(`${tracksEndPoint}?limit=${limit}`, {
method: 'GET',
headers: { 'Authorization' : 'Bearer ' + token}
});
const data = await result.json();
return data.items;
}
const _getTrack = async (token, trackEndPoint) => {
const result = await fetch(`${trackEndPoint}`, {
method: 'GET',
headers: { 'Authorization' : 'Bearer ' + token}
});
const data = await result.json();
return data;
}
return {
getToken() {
return _getToken();
},
getGenres(token) {
return _getGenres(token);
},
getPlaylistByGenre(token, genreId) {
return _getPlaylistByGenre(token, genreId);
},
getTracks(token, tracksEndPoint) {
return _getTracks(token, tracksEndPoint);
},
getTrack(token, trackEndPoint) {
return _getTrack(token, trackEndPoint);
}
}
})();
// UI Module
const UIController = (function() {
//object to hold references to html selectors
const DOMElements = {
selectGenre: '#select_genre',
selectPlaylist: '#select_playlist',
buttonSubmit: '#btn_submit',
divSongDetail: '#song-detail',
hfToken: '#hidden_token',
divSonglist: '.song-list'
}
//public methods
return {
//method to get input fields
inputField() {
return {
genre: document.querySelector(DOMElements.selectGenre),
playlist: document.querySelector(DOMElements.selectPlaylist),
tracks: document.querySelector(DOMElements.divSonglist),
submit: document.querySelector(DOMElements.buttonSubmit),
songDetail: document.querySelector(DOMElements.divSongDetail)
}
},
// need methods to create select list option
createGenre(text, value) {
const html = `<option value="${value}">${text}</option>`;
document.querySelector(DOMElements.selectGenre).insertAdjacentHTML('beforeend', html);
},
createPlaylist(text, value) {
const html = `<option value="${value}">${text}</option>`;
document.querySelector(DOMElements.selectPlaylist).insertAdjacentHTML('beforeend', html);
},
// need method to create a track list group item
createTrack(id, name) {
const html = `<a href="#" class="list-group-item list-group-item-action list-group-item-light" id="${id}">${name}</a>`;
document.querySelector(DOMElements.divSonglist).insertAdjacentHTML('beforeend', html);
},
// need method to create the song detail
createTrackDetail(img, title, artist) {
const detailDiv = document.querySelector(DOMElements.divSongDetail);
// any time user clicks a new song, we need to clear out the song detail div
detailDiv.innerHTML = '';
const html =
`
<div class="row col-sm-12 px-0">
<img src="${img}" alt="">
</div>
<div class="row col-sm-12 px-0">
<label for="Genre" class="form-label col-sm-12">${title}:</label>
</div>
<div class="row col-sm-12 px-0">
<label for="artist" class="form-label col-sm-12">By ${artist}:</label>
</div>
`;
detailDiv.insertAdjacentHTML('beforeend', html)
},
resetTrackDetail() {
this.inputField().songDetail.innerHTML = '';
},
resetTracks() {
this.inputField().tracks.innerHTML = '';
this.resetTrackDetail();
},
resetPlaylist() {
this.inputField().playlist.innerHTML = '';
this.resetTracks();
},
storeToken(value) {
document.querySelector(DOMElements.hfToken).value = value;
},
getStoredToken() {
return {
token: document.querySelector(DOMElements.hfToken).value
}
}
}
})();
const APPController = (function(UICtrl, APICtrl) {
// get input field object ref
const DOMInputs = UICtrl.inputField();
// get genres on page load
const loadGenres = async () => {
//get the token
const token = await APICtrl.getToken();
//store the token onto the page
UICtrl.storeToken(token);
//get the genres
const genres = await APICtrl.getGenres(token);
//populate our genres select element
genres.forEach(element => UICtrl.createGenre(element.name, element.id));
}
// create genre change event listener
DOMInputs.genre.addEventListener('change', async () => {
//reset the playlist
UICtrl.resetPlaylist();
//get the token that's stored on the page
const token = UICtrl.getStoredToken().token;
// get the genre select field
const genreSelect = UICtrl.inputField().genre;
// get the genre id associated with the selected genre
const genreId = genreSelect.options[genreSelect.selectedIndex].value;
// ge the playlist based on a genre
const playlist = await APICtrl.getPlaylistByGenre(token, genreId);
// create a playlist list item for every playlist returned
playlist.forEach(p => UICtrl.createPlaylist(p.name, p.tracks.href));
});
// create submit button click event listener
DOMInputs.submit.addEventListener('click', async (e) => {
// prevent page reset
e.preventDefault();
// clear tracks
UICtrl.resetTracks();
//get the token
const token = UICtrl.getStoredToken().token;
// get the playlist field
const playlistSelect = UICtrl.inputField().playlist;
// get track endpoint based on the selected playlist
const tracksEndPoint = playlistSelect.options[playlistSelect.selectedIndex].value;
// get the list of tracks
const tracks = await APICtrl.getTracks(token, tracksEndPoint);
// create a track list item
tracks.forEach(el => UICtrl.createTrack(el.track.href, el.track.name))
});
// create song selection click event listener
DOMInputs.tracks.addEventListener('click', async (e) => {
// prevent page reset
e.preventDefault();
UICtrl.resetTrackDetail();
// get the token
const token = UICtrl.getStoredToken().token;
// get the track endpoint
const trackEndpoint = e.target.id;
//get the track object
const track = await APICtrl.getTrack(token, trackEndpoint);
// load the track details
UICtrl.createTrackDetail(track.album.images[2].url, track.name, track.artists[0].name);
});
return {
init() {
console.log('App is starting');
loadGenres();
}
}
})(UIController, APIController);
// will need to call a method to load the genres on page load
APPController.init();