diff options
author | mat <github@matdoes.dev> | 2021-12-30 16:56:01 -0600 |
---|---|---|
committer | mat <github@matdoes.dev> | 2021-12-30 16:56:01 -0600 |
commit | 4463fae72839f83a1c98359056c99c6096d3680b (patch) | |
tree | 14118bd78463ac7df3b51139c21b3e9eeadd5364 /src/hypixelApi.ts | |
parent | 2d4168ed9ca0b467c1f4b2208e9c4ed05f98107d (diff) | |
download | skyblock-api-4463fae72839f83a1c98359056c99c6096d3680b.tar.gz skyblock-api-4463fae72839f83a1c98359056c99c6096d3680b.tar.bz2 skyblock-api-4463fae72839f83a1c98359056c99c6096d3680b.zip |
improve api key usage measurement
Diffstat (limited to 'src/hypixelApi.ts')
-rw-r--r-- | src/hypixelApi.ts | 18 |
1 files changed, 12 insertions, 6 deletions
diff --git a/src/hypixelApi.ts b/src/hypixelApi.ts index 1de583b..e4bd7cc 100644 --- a/src/hypixelApi.ts +++ b/src/hypixelApi.ts @@ -26,7 +26,8 @@ interface KeyUsage { } const apiKeyUsage: { [ key: string ]: KeyUsage } = {} - +// the usage amount the api key was on right before it reset +const apiKeyMaxUsage: { [ key: string ]: number } = {} const baseHypixelAPI = 'https://api.hypixel.net' @@ -44,8 +45,10 @@ export function chooseApiKey(): string | null { 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) + if (Date.now() > keyUsage.reset) { + apiKeyMaxUsage[key] = keyUsage.limit - keyUsage.remaining keyUsage.remaining = keyUsage.limit + } // if this key has more uses remaining than the current known best one, save it if (bestKeyUsage === null || keyUsage.remaining > bestKeyUsage.remaining) { @@ -59,9 +62,12 @@ export function chooseApiKey(): string | null { export function getKeyUsage() { let keyLimit = 0 let keyUsage = 0 - for (let key of Object.values(apiKeyUsage)) { - keyLimit += key.limit - keyUsage += key.limit - key.remaining + for (let key of Object.values(apiKeyMaxUsage)) { + // if the key isn't in apiKeyUsage, continue + if (!apiKeyUsage[key]) continue + + keyLimit += apiKeyUsage[key].limit + keyUsage += apiKeyMaxUsage[key] } return { limit: keyLimit, @@ -185,7 +191,7 @@ export let sendApiRequest = async function sendApiRequest({ path, key, args }): apiKeyUsage[key] = { remaining: parseInt(fetchResponse.headers.get('ratelimit-remaining') ?? '0'), limit: parseInt(fetchResponse.headers.get('ratelimit-limit') ?? '0'), - reset: Date.now() + parseInt(fetchResponse.headers.get('ratelimit-reset') ?? '0') * 1000 + reset: Date.now() + parseInt(fetchResponse.headers.get('ratelimit-reset') ?? '0') * 1000, } if (fetchJsonParsed.throttle) { |