Skip to content

Commit

Permalink
Switch to node-fetch from Axios (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
OIRNOIR authored Jun 19, 2022
1 parent d781426 commit 108ddc7
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 74 deletions.
107 changes: 66 additions & 41 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
},
"dependencies": {
"@sapphire/async-queue": "^1.1.4",
"axios": "^0.21.1",
"ms": "^2.1.3",
"node-fetch": "^2.6.7",
"update-notifier": "^5.1.0"
},
"engines": {
Expand Down
82 changes: 54 additions & 28 deletions src/RequestHandler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const axios = require("axios")
const fetch = require('node-fetch');
const { RatelimitError, APIError } = require("./errors")
const { AsyncQueue } = require("@sapphire/async-queue")
const queue = new AsyncQueue()
Expand All @@ -7,40 +7,66 @@ class RequestHandler {
this._client = client
}

async request(endpoint, query = {}, method, body, _attempts = 0) {
async request(endpoint, query = {}, method = "GET", body, _attempts = 0) {
return new Promise(async (resolve, reject) => {
await queue.wait()
// The following function (encode) is stolen from Axios ;p
function encode(str) {
var charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
'%00': '\x00'
};
return encodeURIComponent(str).replace(/[!'\(\)~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
function toQueryString (data) {
if (Object.entries(data).length == 0) return "";
let result = "";
for (const [key, value] of Object.entries(data)) {
result.length == 0 ? result = "?" : result += "&";
result += `${encode(key)}=${encode(value)}`;
}
return result;
}
const url = `${this._client.baseURL}${this._client.version}${endpoint}${toQueryString(query)}`;
const options = {
validateStatus: null,
method,
headers: {
Authorization: this._client.token,
"Content-Type": "application/json",
"Authorization": this._client.token,
"Content-Type": "application/json"
},
baseURL: this._client.baseURL + this._client.version,
url: endpoint,
method: method,
data: body,
params: query,
timeout: 15000,
}

body: (body == null || Object.entries(body).length == 0) ? undefined : JSON.stringify(body),
timeout: 15000
};
if (this._client.debug) console.debug(`Sending request to ${options.url}\nMethod:\n ${options.method}\nParams:\n ${query}`)
try {
axios.request(options).then((res) => {
// Increase the number of attempts
++_attempts

if (res.status >= 200 && res.status < 300) {
resolve(res.data)
if (this._client.debug) console.debug("Success: \n", res.data)
} else if (res.status === 429) {
if (this._client.debug) console.debug("Ratelimited: \n", res)
reject(new RatelimitError(res))
} else {
if (this._client.debug) console.debug("API Error: \n", res)
reject(new APIError(res))
}
})
const res = await fetch(url, options);
if (res.status >= 200 && res.status < 300) {
const json = await res.json();
resolve(json);
if (this._client.debug) console.debug("Success: \n", json);
} else if (res.status === 429) {
const json = await res.json();
if (this._client.debug) console.debug("Ratelimited: \n", res, json);
reject(new RatelimitError(res, json));
} else {
try {
const json = await res.json();
if (this._client.debug) console.debug("API Error: \n", res, json)
reject(new APIError(res, json));
} catch (err) {
if (this._client.debug) console.debug("API Error: \n", res)
reject(new APIError(res, null))
}
}
} catch (err) {
reject(err);
} finally {
queue.shift()
}
Expand Down
4 changes: 2 additions & 2 deletions src/errors/APIError.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
*/

class APIError extends Error {
constructor(response) {
constructor(response, data) {
super();
this.name = this.constructor.name;
this.status = response.status;
this.message = response.data ? response.data.error : undefined
this.message = data ? data.error : undefined
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/errors/RatelimitError.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ const ms = require("ms")
*/

class RatelimitError extends Error {
constructor(response) {
constructor(response, data) {
super();
this.name = this.constructor.name;
this.status = response.status;
this.remaining = response.data["Ratelimit-Remaining"]
this.remaining = data["Ratelimit-Remaining"]
this.message = 'You are currently ratelimited! Try again in ' + ms(this.remaining)
}
}
Expand Down

0 comments on commit 108ddc7

Please sign in to comment.