aboutsummaryrefslogtreecommitdiff
path: root/build/hypixelApi.js
diff options
context:
space:
mode:
Diffstat (limited to 'build/hypixelApi.js')
-rw-r--r--build/hypixelApi.js66
1 files changed, 66 insertions, 0 deletions
diff --git a/build/hypixelApi.js b/build/hypixelApi.js
new file mode 100644
index 0000000..5cbd829
--- /dev/null
+++ b/build/hypixelApi.js
@@ -0,0 +1,66 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.sendApiRequest = exports.chooseApiKey = void 0;
+const node_fetch_1 = __importDefault(require("node-fetch"));
+const util_1 = require("./util");
+const https_1 = require("https");
+require('dotenv').config();
+// We need to create an agent to prevent memory leaks and to only do dns lookups once
+const httpsAgent = new https_1.Agent({
+ keepAlive: true
+});
+/* Lower level code related to the Hypixel api */
+const apiKeys = process.env.keys.split(' ');
+const apiKeyUsage = {};
+const baseHypixelAPI = 'https://api.hypixel.net';
+/** Choose the best current API key */
+function chooseApiKey() {
+ // find the api key with the lowest amount of uses
+ let bestKeyUsage = null;
+ let bestKey = null;
+ for (var key of util_1.shuffle(apiKeys)) {
+ const keyUsage = apiKeyUsage[key];
+ // if the key has never been used before, use it
+ if (!keyUsage)
+ return key;
+ // if the key has reset since the last use, set the remaining count to the default
+ if (Date.now() > keyUsage.reset)
+ keyUsage.remaining = keyUsage.limit;
+ // if this key has more uses remaining than the current known best one, save it
+ if (!bestKeyUsage || keyUsage.remaining > bestKeyUsage.remaining) {
+ bestKeyUsage = keyUsage;
+ bestKey = key;
+ }
+ }
+ return bestKey;
+}
+exports.chooseApiKey = chooseApiKey;
+/** Send an HTTP request to the Hypixel API */
+async function sendApiRequest({ path, key, args }) {
+ console.log('sending api request to', path, args);
+ // Send a raw http request to api.hypixel.net, and return the parsed json
+ if (key)
+ // If there's an api key, add it to the arguments
+ args.key = key;
+ // Construct a url from the base api url, path, and arguments
+ const fetchUrl = baseHypixelAPI + '/' + path + '?' + util_1.jsonToQuery(args);
+ const fetchResponse = await node_fetch_1.default(fetchUrl, { agent: () => httpsAgent });
+ if (fetchResponse.headers['ratelimit-limit'])
+ // remember how many uses it has
+ apiKeyUsage[key] = {
+ remaining: fetchResponse.headers['ratelimit-remaining'],
+ limit: fetchResponse.headers['ratelimit-limit'],
+ reset: Date.now() + parseInt(fetchResponse.headers['ratelimit-reset']) * 1000
+ };
+ const fetchJsonParsed = await fetchResponse.json();
+ if (fetchJsonParsed.throttle) {
+ apiKeyUsage[key].remaining = 0;
+ console.log('throttled :(');
+ return { throttled: true };
+ }
+ return fetchJsonParsed;
+}
+exports.sendApiRequest = sendApiRequest;