-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.ts
68 lines (57 loc) · 1.48 KB
/
utils.ts
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
import { URLS } from "./constants";
import { AccessToken, Endpoint } from "./types";
export async function spotifyFetch<T>(
endpoint: Endpoint,
token?: string,
method: string = "GET",
body?: any
): Promise<T> {
if (!token) {
token = (await getAccessToken()).access_token;
}
const options = {
method,
headers: {
Authorization: `Bearer ${token}`,
},
};
if (method == "POST" && body) {
Object.assign(options, { body: JSON.stringify(body) });
}
console.log("fetching: ", endpoint);
const data = await fetch(endpoint, options).then((res) => res.json());
return data;
}
export async function getAccessToken(
id?: string,
client?: string,
refresh?: string
): Promise<AccessToken> {
if (!id) {
id = process.env.SPOTIFY_CLIENT_ID;
}
if (!client) {
client = process.env.SPOTIFY_CLIENT_SECRET;
}
if (!refresh) {
refresh = process.env.SPOTIFY_REFRESH_TOKEN;
}
if (!id || !client || !refresh) {
throw new Error(
`You are missing a Spotify ENV Variable: [ id: ${id}, client: ${client}, refresh: ${refresh} ]`
);
}
const basic = Buffer.from(`${id}:${client}`).toString("base64");
const getTokenResponse = await fetch(URLS.Token, {
method: "POST",
headers: {
Authorization: `Basic ${basic}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refresh,
}),
});
return getTokenResponse.json();
}