-
Notifications
You must be signed in to change notification settings - Fork 1
/
companion-api-client.js
98 lines (83 loc) · 2.12 KB
/
companion-api-client.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
/* global module */
'use strict'
const antiHammerInterval = 5000
const httpOkStatus = 200
const httpNoContent = 204
const maxJournalRetries = 10
const userAgent = 'Fuel Rats Journal Reader https://journal.fuelrats.com. Contact author at: [email protected]'
let numberOfRetries = 0
class CompanionApiClient {
constructor (accessToken) {
this.AccessToken = accessToken
}
async fetchProfile () {
const profile = await this.fetchData('profile')
return profile
}
async fetchMarket () {
const market = await this.fetchData('market')
return market
}
async fetchShipyard () {
const shipyard = await this.fetchData('shipyard')
return shipyard
}
async fetchTodaysJournal () {
if (numberOfRetries > maxJournalRetries) {
return null
}
const journal = await this.fetchDataAsText('journal')
if (!journal.completeResult) {
await new Promise((resolve) => setTimeout(resolve, antiHammerInterval))
numberOfRetries += 1
return this.fetchTodaysJournal()
}
return journal
}
async fetchDataAsText (endpoint) {
let completeResult = false
const result = await fetch(`https://companion.orerve.net/${endpoint}`, {
headers: {
Authorization: `Bearer ${this.AccessToken}`,
'X-User-Agent': userAgent,
},
})
.then((resp) => {
if (resp.status === httpOkStatus || resp.status === httpNoContent) {
completeResult = true
}
return resp.text()
})
.catch((err) => {
console.error(err)
return {
error: true,
message: err,
}
})
return {
completeResult,
result,
}
}
async fetchData (endpoint) {
const result = await fetch(`https://companion.orerve.net/${endpoint}`, {
headers: {
Authorization: `Bearer ${this.AccessToken}`,
'X-User-Agent': userAgent,
},
})
.then((resp) => resp.json())
.catch((err) => {
console.error(err)
return {
error: true,
message: err,
}
})
return result
}
}
module.exports = {
CompanionApiClient,
}