-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI_requests.js
More file actions
86 lines (69 loc) · 2.5 KB
/
Copy pathAPI_requests.js
File metadata and controls
86 lines (69 loc) · 2.5 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
83
84
85
86
'use server'
const access_key_url = `https://oauth.battle.net/token`;
if (!process.env.CLIENT_ID || !process.env.CLIENT_SECRET) {
console.error("❌ Missing CLIENT_ID or CLIENT_SECRET");
}
const btoa_secret_id = btoa(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`);
let access_key = null;
async function getAccessToken() {
const response = await fetch(access_key_url, {
method: "POST",
headers: {
"Authorization": `Basic ${btoa_secret_id}`,
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams({ grant_type: "client_credentials" })
});
if (!response.ok) {
const text = await response.text();
console.error(`Token request failed: ${response.status} ${response.statusText}\n${text}`);
throw new Error("Failed to obtain access token.");
}
const data = await response.json();
access_key = data.access_token;
return data.access_token;
}
function get_key() {
if (!access_key) {
return getAccessToken().then((key) => {
access_key = key;
return key;
});
}
else {
return Promise.resolve(access_key);
}
}
async function fetchResponse(url) {
const key = await get_key();
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${key}`
}
});
if (!response.ok) {
const text = await response.text();
console.error(`API error: ${response.status} ${response.statusText}\n${text}`);
throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
}
const text = await response.text();
if (!text) {
throw new Error(`Empty response from API for ${url}`);
}
try {
return JSON.parse(text);
} catch (err) {
console.error(`JSON parse error for ${url}:`, text);
throw err;
}
}
async function GetSeasonIndex(region) {
return await fetchResponse(`https://${region || 'us'}.api.blizzard.com/data/d3/season/`);
}
async function GetSeasonLeaderboardTypes(region,season) {
return await fetchResponse(`https://${region || 'us'}.api.blizzard.com/data/d3/season/${season || 1}`);
}
async function GetSeasonalLeaderboard(region,season,leaderboard) {
return await fetchResponse(`https://${region || 'us'}.api.blizzard.com/data/d3/season/${season || 1}/leaderboard/${leaderboard || 'achievement-points'}`);
}
export { GetSeasonIndex, GetSeasonLeaderboardTypes, GetSeasonalLeaderboard };