-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
82 lines (73 loc) · 2.44 KB
/
api.js
File metadata and controls
82 lines (73 loc) · 2.44 KB
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
export function getToken() {
return sessionStorage.getItem("access_token");
}
export async function getUserProfile() {
const token = getToken();
const res = await fetch("https://api.spotify.com/v1/me", {
headers: { Authorization: `Bearer ${token}` }
});
return res.json();
}
export async function getTopArtists(limit = 5) {
const token = getToken();
const res = await fetch(`https://api.spotify.com/v1/me/top/artists?limit=${limit}`, {
headers: { Authorization: `Bearer ${token}` }
});
return res.json();
}
export async function searchSpotify(query) {
if (!query || query.trim().length < 2) {
return { tracks: { items: [] }, artists: { items: [] }, albums: { items: [] } };
}
const token = getToken();
const res = await fetch(`https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=track,artist,album&limit=10`, {
headers: { Authorization: `Bearer ${token}` }
});
return res.json();
}
export async function getSavedAlbums(limit = 5) {
const token = getToken();
const res = await fetch(`https://api.spotify.com/v1/me/albums?limit=${limit}`, {
headers: { Authorization: `Bearer ${token}` }
});
return res.json();
}
export async function getAlbumTracks(albumId) {
const token = getToken();
const res = await fetch(`https://api.spotify.com/v1/albums/${albumId}/tracks?limit=50`, {
headers: { Authorization: `Bearer ${token}` }
});
return res.json();
}
export async function playTrack(deviceId, trackUri) {
const token = getToken();
const res = await fetch(`https://api.spotify.com/v1/me/player/play?device_id=${deviceId}`, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ uris: [trackUri] })
});
return res.status === 204;
}
export async function pauseTrack(deviceId) {
const token = getToken();
const res = await fetch(`https://api.spotify.com/v1/me/player/pause?device_id=${deviceId}`, {
method: "PUT",
headers: { Authorization: `Bearer ${token}` }
});
return res.status === 204;
}
export async function transferPlayback(deviceId, shouldPlay = false) {
const token = getToken();
const res = await fetch("https://api.spotify.com/v1/me/player", {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ device_ids: [deviceId], play: shouldPlay })
});
return res.status === 204;
}