optimize loading time

This commit is contained in:
MuslemRahimi 2025-02-09 18:02:41 +01:00
parent f330a64f82
commit ebfe0ed017
3 changed files with 162 additions and 97 deletions

View File

@ -18,6 +18,7 @@ const cleanString = (input) => {
}; };
const fetchData = async (apiURL, apiKey, endpoint, ticker) => { const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
try {
const response = await fetch(`${apiURL}${endpoint}`, { const response = await fetch(`${apiURL}${endpoint}`, {
method: "POST", method: "POST",
headers: { headers: {
@ -26,7 +27,17 @@ const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
}, },
body: JSON.stringify({ ticker }), body: JSON.stringify({ ticker }),
}); });
return response.json();
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Error fetching ${endpoint}:`, error);
return [];
}
}; };
const fetchWatchlist = async (pb, userId) => { const fetchWatchlist = async (pb, userId) => {
@ -46,6 +57,7 @@ export const load = async ({ params, locals }) => {
const { apiURL, apiKey, pb, user } = locals; const { apiURL, apiKey, pb, user } = locals;
const { tickerID } = params; const { tickerID } = params;
try {
const endpoints = [ const endpoints = [
"/etf-profile", "/etf-profile",
"/etf-holdings", "/etf-holdings",
@ -78,20 +90,35 @@ export const load = async ({ params, locals }) => {
getUserWatchlist, getUserWatchlist,
] = await Promise.all(promises); ] = await Promise.all(promises);
return { return {
getETFProfile, getETFProfile: getETFProfile || [],
getETFHoldings, getETFHoldings: getETFHoldings || [],
getETFSectorWeighting, getETFSectorWeighting: getETFSectorWeighting || [],
getStockDividend, getStockDividend: getStockDividend || [],
getStockQuote, getStockQuote: getStockQuote || [],
getPrePostQuote, getPrePostQuote: getPrePostQuote || [],
getWhyPriceMoved, getWhyPriceMoved: getWhyPriceMoved || [],
getOneDayPrice, getOneDayPrice: getOneDayPrice || [],
getNews, getNews: getNews || [],
getUserWatchlist, getUserWatchlist: getUserWatchlist || [],
companyName: cleanString(getETFProfile?.at(0)?.name), companyName: cleanString(getETFProfile?.at(0)?.name),
getParams: params.tickerID, getParams: params.tickerID,
}; };
} catch (error) {
console.error('Error in load function:', error);
return {
getETFProfile: [],
getETFHoldings: [],
getETFSectorWeighting: [],
getStockDividend: [],
getStockQuote: [],
getPrePostQuote: [],
getWhyPriceMoved: [],
getOneDayPrice: [],
getNews: [],
getUserWatchlist: [],
companyName: '',
getParams: params.tickerID,
};
}
}; };

View File

@ -267,7 +267,6 @@
rawData = prepareDataset(data?.getData, timePeriod); rawData = prepareDataset(data?.getData, timePeriod);
originalData = rawData; originalData = rawData;
stockList = rawData?.slice(0, 50); stockList = rawData?.slice(0, 50);
console.log(rawData);
isLoaded = true; isLoaded = true;
} }
} }

View File

@ -17,7 +17,22 @@ const cleanString = (input) => {
return input?.replace(pattern, "").trim(); return input?.replace(pattern, "").trim();
}; };
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds
const REQUEST_TIMEOUT = 5000; // 5 seconds
const cache = new Map();
const fetchData = async (apiURL, apiKey, endpoint, ticker) => { const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
const cacheKey = `${endpoint}-${ticker}`;
const cached = cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
return cached.data;
}
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT);
try {
const response = await fetch(`${apiURL}${endpoint}`, { const response = await fetch(`${apiURL}${endpoint}`, {
method: "POST", method: "POST",
headers: { headers: {
@ -25,8 +40,24 @@ const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
"X-API-KEY": apiKey, "X-API-KEY": apiKey,
}, },
body: JSON.stringify({ ticker }), body: JSON.stringify({ ticker }),
signal: controller.signal
}); });
return response.json();
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
cache.set(cacheKey, { data, timestamp: Date.now() });
return data;
} catch (error) {
if (error.name === 'AbortError') {
throw new Error(`Request timeout for ${endpoint}`);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}; };
const fetchWatchlist = async (pb, userId) => { const fetchWatchlist = async (pb, userId) => {
@ -58,13 +89,11 @@ export const load = async ({ params, locals }) => {
"/stock-news", "/stock-news",
]; ];
const promises = [ if (!tickerID) {
...endpoints.map((endpoint) => return { error: 'Invalid ticker ID' };
fetchData(apiURL, apiKey, endpoint, tickerID), }
),
fetchWatchlist(pb, user?.id),
];
try {
const [ const [
getStockDeck, getStockDeck,
getAnalystRating, getAnalystRating,
@ -76,9 +105,16 @@ export const load = async ({ params, locals }) => {
getEarningsSurprise, getEarningsSurprise,
getNews, getNews,
getUserWatchlist, getUserWatchlist,
] = await Promise.all(promises); ] = await Promise.all([
...endpoints.map((endpoint) =>
fetchData(apiURL, apiKey, endpoint, tickerID).catch(error => ({ error: error.message }))
),
fetchWatchlist(pb, user?.id).catch(() => [])
]);
if (!getStockDeck || getStockDeck.error) {
return { error: 'Failed to fetch stock data' };
}
return { return {
getStockDeck, getStockDeck,
@ -94,4 +130,7 @@ export const load = async ({ params, locals }) => {
companyName: cleanString(getStockDeck?.companyName), companyName: cleanString(getStockDeck?.companyName),
getParams: params.tickerID, getParams: params.tickerID,
}; };
} catch (error) {
return { error: 'Failed to load stock data' };
}
}; };