-
Notifications
You must be signed in to change notification settings - Fork 38
/
twitch-api.js
75 lines (68 loc) · 2.06 KB
/
twitch-api.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
const axios = require('axios');
const config = require('./config.json');
/**
* Twitch Helix API helper ("New Twitch API").
*/
class TwitchApi {
static get requestOptions() {
// Automatically remove "oauth:" prefix if it's present
const oauthPrefix = "oauth:";
let oauthBearer = config.twitch_oauth_token;
if (oauthBearer.startsWith(oauthPrefix)) {
oauthBearer = oauthBearer.substr(oauthPrefix.length);
}
// Construct default request options
return {
baseURL: "https://api.twitch.tv/helix/",
headers: {
"Client-ID": config.twitch_client_id,
"Authorization": `Bearer ${oauthBearer}`
}
};
}
static handleApiError(err) {
const res = err.response || { };
if (res.data && res.data.message) {
console.error('[TwitchApi]', 'API request failed with Helix error:', res.data.message, `(${res.data.error}/${res.data.status})`);
} else {
console.error('[TwitchApi]', 'API request failed with error:', err.message || err);
}
}
static fetchStreams(channelNames) {
return new Promise((resolve, reject) => {
axios.get(`/streams?user_login=${channelNames.join('&user_login=')}`, this.requestOptions)
.then((res) => {
resolve(res.data.data || []);
})
.catch((err) => {
this.handleApiError(err);
reject(err);
});
});
}
static fetchUsers(channelNames) {
return new Promise((resolve, reject) => {
axios.get(`/users?login=${channelNames.join('&login=')}`, this.requestOptions)
.then((res) => {
resolve(res.data.data || []);
})
.catch((err) => {
this.handleApiError(err);
reject(err);
});
});
}
static fetchGames(gameIds) {
return new Promise((resolve, reject) => {
axios.get(`/games?id=${gameIds.join('&id=')}`, this.requestOptions)
.then((res) => {
resolve(res.data.data || []);
})
.catch((err) => {
this.handleApiError(err);
reject(err);
});
});
}
}
module.exports = TwitchApi;