cahce apraisal

This commit is contained in:
2023-09-23 10:56:17 +02:00
parent 1c882e0d1c
commit 14b2f01ef1
3 changed files with 42 additions and 11 deletions

View File

@@ -1,4 +1,6 @@
import { evepraisalAxiosInstance } from '@/service';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { MarketType } from "./type";
export type MarketTypePrice = {
@@ -7,9 +9,35 @@ export type MarketTypePrice = {
sell: number
}
export const getPrice = async (type: MarketType): Promise<MarketTypePrice> => (await getPrices([type]))[0];
export const getPrices = async (types: MarketType[]): Promise<MarketTypePrice[]> => (await evepraisalAxiosInstance.post(`/appraisal.json?market=jita&persist=no&raw_textarea=${types.map(t => t.name).join("%0A")}`)).data.appraisal.items.map((item: any) => ({
type: types.find(t => t.name === item.typeName),
buy: item.prices.buy.max,
sell: item.prices.sell.min
}));
type MarketTypePriceCache = {
price: MarketTypePrice,
date: Date
}
const cacheDuration = 1000 * 60 * 5; // 5 minutes
export const useApraisalStore = defineStore('appraisal', () => {
const cache = ref<Record<number, MarketTypePriceCache>>({});
const getPricesUncached = async (types: MarketType[]): Promise<MarketTypePrice[]> => (await evepraisalAxiosInstance.post(`/appraisal.json?market=jita&persist=no&raw_textarea=${types.map(t => t.name).join("%0A")}`)).data.appraisal.items.map((item: any) => ({
type: types.find(t => t.name === item.typeName),
buy: item.prices.buy.max,
sell: item.prices.sell.min
}));
const getPrice = async (type: MarketType): Promise<MarketTypePrice> => (await getPrices([type]))[0];
const getPrices = async (types: MarketType[]): Promise<MarketTypePrice[]> => {
const now = new Date().getTime();
const cached = types.map(t => cache.value[t.id]).filter(c => c && now - c.date.getTime() < cacheDuration);
const uncached = types.filter(t => !cached.find(c => c.price.type.id === t.id));
if (uncached.length > 0) {
const prices = await getPricesUncached(uncached);
prices.forEach(p => cache.value[p.type.id] = { price: p, date: new Date() });
return [...cached.map(c => c.price), ...prices];
}
return cached.map(c => c.price);
};
return { getPrice, getPrices };
});