fix: allow retries if API fails

This commit is contained in:
xenticore
2025-04-07 13:30:39 -04:00
parent fa7276a53c
commit df2e8ede6d

View File

@@ -1,5 +1,6 @@
declare function GM_fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> declare function GM_fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>
import '../GM_fetch' import '../GM_fetch'
import { logDebug } from '../utils/log'
async function getPricesToken(): Promise<string> { async function getPricesToken(): Promise<string> {
return new Promise<any>((resolve, reject) => { return new Promise<any>((resolve, reject) => {
@@ -37,7 +38,7 @@ class PricesResponse {
* @returns {Promise<PricesResponse>} Object containing 'keys' and 'metal' prices * @returns {Promise<PricesResponse>} Object containing 'keys' and 'metal' prices
* @throws When authentication fails or API returns non-200 status code * @throws When authentication fails or API returns non-200 status code
*/ */
async function priceUsingPricesTF(token: string, sku: string): Promise<PricesResponse> { async function priceUsingPricesTF(token: string, sku: string, retries: number = 3): Promise<PricesResponse> {
// prices.tf // prices.tf
// https://api2.prices.tf/prices/${sku} // https://api2.prices.tf/prices/${sku}
// Authorization: Bearer ${token} // Authorization: Bearer ${token}
@@ -65,11 +66,37 @@ async function priceUsingPricesTF(token: string, sku: string): Promise<PricesRes
}) })
} }
} }
if (response.status === 200) { switch (response.status) {
const json = await response.json() case 200:
resolve({ keys: json['sellKeys'], metal: json['sellHalfScrap'] / 18.0 }) const json = await response.json()
} else { resolve({ keys: json['sellKeys'], metal: json['sellHalfScrap'] / 18.0 })
reject(response.status) break;
case 404:
reject("Not found in prices.tf")
break;
case 429:
case 503:
// Happens if we send too many requests in a short period of time
// Retry after a few seconds
if(retries > 0) {
logDebug(`Cloudflare rate limit exceeded, trying again after 2 seconds, ${retries} retries left`)
await new Promise(resolve => setTimeout(resolve, 2000));
try {
const retryResult = await priceUsingPricesTF(token, sku, retries - 1);
resolve(retryResult);
} catch (err) {
reject(err);
}
} else {
reject("Cloudflare rate limit exceeded, stopping")
}
break;
default:
// Something went wrong
logDebug(`Received ${response.status} error while pricing ${sku}`)
logDebug(`${JSON.stringify(response.headers)}`)
reject("Unknown error")
break;
} }
}) })
} }