refactor: rewrite async promise as promise chain

This commit is contained in:
xenticore
2025-04-29 00:49:32 -04:00
parent 60e845ddf8
commit 6fdc6fd132

View File

@@ -1,6 +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' import { logDebug, logError } from '../utils/log'
async function getPricesToken(): Promise<string> { async function getPricesToken(): Promise<string> {
return new Promise<string>((resolve, reject) => { return new Promise<string>((resolve, reject) => {
@@ -42,62 +42,48 @@ async function priceUsingPricesTF(token: string, sku: string, retries: number =
// prices.tf // prices.tf
// https://api2.prices.tf/prices/${sku} // https://api2.prices.tf/prices/${sku}
// Authorization: Bearer ${token} // Authorization: Bearer ${token}
return new Promise(async (resolve, reject) => { return GM_fetch(`https://api2.prices.tf/prices/${encodeURIComponent(sku)}`, {
if (!token) {
reject(401)
}
let response = await GM_fetch(`https://api2.prices.tf/prices/${encodeURIComponent(sku)}`, {
method: 'get', method: 'get',
headers: new Headers({ headers: {
'Accept': 'application/json', 'Accept': 'application/json',
'Authorization': `Bearer ${token}` 'Authorization': `Bearer ${token}`,
}
}) })
}) .then(response => {
if (response.status === 404 && sku.includes(';')) { if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
if (response.status === 404 && sku.includes(';') && !sku.includes(';uncraftable')) {
const quality: number = parseInt(sku.split(';')[1], 10); const quality: number = parseInt(sku.split(';')[1], 10);
if(quality === 6) { if(quality === 6) {
// Try uncraftable variant if unique weapon // Try uncraftable variant if unique weapon
response = await GM_fetch(`https://api2.prices.tf/prices/${encodeURIComponent(sku + ';uncraftable')}`, { return priceUsingPricesTF(token, sku + ';uncraftable', retries);
method: 'get',
headers: new Headers({
'Accept': 'application/json',
'Authorization': `Bearer ${token}`
})
})
} }
} }
switch (response.status) { if(response.status === 404) {
case 200: throw new Error(`Item not found: ${sku}`);
const json = await response.json() }
resolve({ keys: json['sellKeys'], metal: json['sellHalfScrap'] / 18.0 }) if(response.status === 503) {
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 // Happens if we send too many requests in a short period of time
// Retry after a few seconds // Retry after a few seconds
if(retries > 0) { if(retries > 0) {
logDebug(`Cloudflare rate limit exceeded, trying again after 2 seconds, ${retries} retries left`) logDebug(`Cloudflare rate limit exceeded, trying again after 2 seconds, ${retries} retries left`)
await new Promise(resolve => setTimeout(resolve, 2000)); return priceUsingPricesTF(token, sku, retries - 1);
try {
const retryResult = await priceUsingPricesTF(token, sku, retries - 1);
resolve(retryResult);
} catch (err) {
reject(err);
}
} else { } else {
reject("Cloudflare rate limit exceeded, stopping") throw new Error(`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;
} }
return response.json();
})
.then(data => {
const prices = new PricesResponse();
prices.keys = data['sellKeys']
prices.metal = data['sellHalfScrap'] / 18.0;
return prices;
})
.catch(error => {
logError(`Failed to fetch prices from prices.tf for item ${sku}`)
throw error;
}) })
} }