You've already forked tf2wikipricing
82 lines
2.5 KiB
TypeScript
82 lines
2.5 KiB
TypeScript
import { defindex_key, storage_priceprefix } from "./config"
|
|
import { priceUsingPricedb } from "./pricing/pricedb"
|
|
import { getStorageValue, setStorageValue } from "./storage"
|
|
import { logDebug } from "./utils/log"
|
|
declare const __ENV_WEBEXTENSION: boolean;
|
|
declare const __ENV_USERSCRIPT: boolean;
|
|
|
|
/** Pricing data for a given TF2 item. */
|
|
export class ItemPriceData {
|
|
/** Item SKU. */
|
|
sku: string
|
|
/** Date updated, as Unix timestamp. */
|
|
update: number
|
|
/** TTL in milliseconds. */
|
|
ttl: number
|
|
/** Price in keys. */
|
|
keys: number
|
|
/** Price in refined metal. */
|
|
metal: number
|
|
/** Steam Community Market price. */
|
|
scmPrice: number
|
|
|
|
toString(): string {
|
|
return `Price for ${this.sku}, fetched ${new Date(this.update)} (expires ${new Date(this.update + this.ttl)})\n` +
|
|
JSON.stringify({
|
|
keys: this.keys,
|
|
metal: this.metal,
|
|
scmPrice: this.scmPrice
|
|
})
|
|
}
|
|
}
|
|
|
|
|
|
export async function fetchKeyPrice() {
|
|
return fetchPrice(`${defindex_key};6`, new Date(), 86400000)
|
|
}
|
|
|
|
/**
|
|
* Fetch a price for a given SKU, using cached values if available.
|
|
* @param update Date retrieved.
|
|
* @param ttl Time to cache results in milliseconds. 30 minutes by default.
|
|
*/
|
|
export async function fetchPrice(sku: string, update: Date = new Date(), ttl: number = 30 * 60 * 1000): Promise<ItemPriceData> {
|
|
let data: ItemPriceData | null
|
|
|
|
const cached: ItemPriceData = await getStorageValue(storage_priceprefix + sku, null)
|
|
if (cached != null && 'keys' in cached && 'metal' in cached && !isNaN(cached.update)) {
|
|
data = cached
|
|
}
|
|
|
|
if (!data || data.sku != sku || 'update' in data && 'ttl' in data && Date.now() > (new Date(data.update).getTime() + data.ttl)) {
|
|
logDebug(`Fetching price data for ${sku}`)
|
|
data = new ItemPriceData()
|
|
data.sku = sku
|
|
data.update = update.getTime()
|
|
data.ttl = ttl
|
|
|
|
try {
|
|
let response: PricesResponse
|
|
if(__ENV_USERSCRIPT) {
|
|
response = await priceUsingPricedb(sku)
|
|
} else {
|
|
response = await chrome.runtime.sendMessage({contentScriptQuery: "priceSKU", sku: sku});
|
|
}
|
|
if (!response || response instanceof Error) {
|
|
throw new Error(`Bad response: ${response}`)
|
|
}
|
|
data.keys = response.keys
|
|
data.metal = response.metal
|
|
} catch (error) {
|
|
throw new Error(`Received "${error}" error while pricing ${sku} using pricedb.io`)
|
|
}
|
|
|
|
if ('metal' in data && 'keys' in data) {
|
|
await setStorageValue(storage_priceprefix + sku, data)
|
|
}
|
|
} else {
|
|
logDebug(`Using cached price data for ${sku}`)
|
|
}
|
|
return data
|
|
}
|