Files
tf2wikipricing/src/background/background.ts

86 lines
2.7 KiB
TypeScript

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == "queryExchangeRates") {
const url = "https://open.er-api.com/v6/latest/USD";
fetch(url)
.then(response => response.json())
.then(json => sendResponse(json))
.catch(error => {
console.error("Failed to get exchange rates", error);
})
return true;
}
})
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == "querySchema") {
const url = "https://raw.githubusercontent.com/danocmx/node-tf2-static-schema/master/static/items.json";
fetch(url)
.then(response => response.json())
.then(json => sendResponse(json))
.catch(error => {
console.error("Failed to get schema", error);
})
return true;
}
}
);
class PricesResponse {
keys: number
metal: number
}
async function priceUsingPricedb(sku: string, retries: number = 3): Promise<PricesResponse> {
const url = `https://pricedb.io/api/item/${encodeURIComponent(sku)}`;
const response = await fetch(url, {
method: 'get',
headers: {
'Accept': 'application/json',
}
})
if (response.status === 404 && sku.includes(';') && !sku.includes(';uncraftable')) {
const quality: number = parseInt(sku.split(';')[1], 10);
if(quality === 6) {
// Try uncraftable variant if unique weapon
return priceUsingPricedb(sku + ';uncraftable');
}
}
if(response.status === 429) {
// Happens if we send too many requests (rate limit: 180 req/min)
// Retry after a few seconds
if(retries >= 0) {
console.log(`Rate limit exceeded, trying again after 1 second, ${retries} retries left`)
await new Promise(resolve => setTimeout(resolve, 1000));
return priceUsingPricedb(sku, retries - 1);
} else {
throw new Error(`Rate limit exceeded, stopping`)
}
}
if (!response.ok) {
throw new Error(`Pricing request for ${sku} failed with status code: ${response.status}`);
}
const data = await response.json();
const prices = new PricesResponse();
prices.keys = data.sell.keys
prices.metal = data.sell.metal
return prices;
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == "priceSKU") {
const sku: string = request.sku
priceUsingPricedb(sku)
.then((response) => sendResponse(response))
.catch(error => {
console.error(`Received "${error}" error while pricing ${sku} using pricedb.io`)
sendResponse(null);
return false;
})
}
return true;
}
);