bugfixing

This commit is contained in:
MuslemRahimi 2025-02-22 22:17:32 +01:00
parent 1411cde332
commit f602c1a1d0

View File

@ -32,20 +32,14 @@ const cleanString = (() => {
const CACHE_DURATION = 5 * 60 * 1000; const CACHE_DURATION = 5 * 60 * 1000;
const REQUEST_TIMEOUT = 5000; const REQUEST_TIMEOUT = 5000;
const ENDPOINTS = Object.freeze([ const ENDPOINTS = Object.freeze([
"/index-profile", "/stockdeck",
"/etf-holdings", "/analyst-summary-rating",
"/etf-sector-weighting",
"/stock-quote", "/stock-quote",
"/pre-post-quote", "/pre-post-quote",
"/wiim", "/wiim",
"/one-day-price", "/one-day-price",
"/stock-news" "/next-earnings",
]); "/earnings-surprise",
const SPY_PROXY_ENDPOINTS = Object.freeze([
"/etf-holdings",
"/etf-sector-weighting",
"/wiim",
"/stock-news" "/stock-news"
]); ]);
@ -94,13 +88,9 @@ const fetchWithTimeout = async (url, options, timeout) => {
} }
}; };
// Main data fetching function with SPX/SPY handling // Main data fetching function
const fetchData = async (apiURL, apiKey, endpoint, ticker) => { const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
const useSpyTicker = ticker?.toLowerCase() === "^spx" && const cacheKey = `${endpoint}-${ticker}`;
SPY_PROXY_ENDPOINTS.some(proxyEndpoint => ENDPOINTS.includes(proxyEndpoint));
const effectiveTicker = useSpyTicker ? "SPY" : ticker;
const cacheKey = `${endpoint}-${effectiveTicker}`;
const cachedData = dataCache.get(cacheKey); const cachedData = dataCache.get(cacheKey);
if (cachedData) return cachedData; if (cachedData) return cachedData;
@ -110,10 +100,7 @@ const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
"Content-Type": "application/json", "Content-Type": "application/json",
"X-API-KEY": apiKey "X-API-KEY": apiKey
}, },
body: JSON.stringify({ body: JSON.stringify({ ticker, endpoints: ENDPOINTS })
ticker: effectiveTicker,
endpoints: ENDPOINTS
})
}; };
try { try {
@ -144,64 +131,50 @@ const fetchWatchlist = async (pb, userId) => {
} }
}; };
// Helper function to generate default response
const getDefaultResponse = (tickerID) => ({
getIndexProfile: [],
getIndexHolding: [],
getIndexSectorWeighting: [],
getStockQuote: [],
getPrePostQuote: [],
getWhyPriceMoved: [],
getOneDayPrice: [],
getNews: [],
getUserWatchlist: [],
companyName: '',
getParams: tickerID
});
// Main load function with parallel fetching // Main load function with parallel fetching
export const load = async ({ params, locals }) => { export const load = async ({ params, locals }) => {
const { apiURL, apiKey, pb, user } = locals; const { apiURL, apiKey, pb, user } = locals;
const { tickerID } = params; const { tickerID } = params;
if (!tickerID) { if (!tickerID) {
return getDefaultResponse(tickerID); return { error: 'Invalid ticker ID' };
} }
try { try {
// Fetch data in parallel // Fetch data in parallel
const [indexData, userWatchlist] = await Promise.all([ const [stockData, userWatchlist] = await Promise.all([
fetchData(apiURL, apiKey, "/bulk-data", tickerID), fetchData(apiURL, apiKey, "/bulk-data", tickerID),
fetchWatchlist(pb, user?.id) fetchWatchlist(pb, user?.id)
]); ]);
// Destructure with default empty arrays to prevent undefined errors // Destructure with default empty object to prevent undefined errors
const { const {
'/index-profile': getIndexProfile = [], '/stockdeck': getStockDeck = {},
'/etf-holdings': getIndexHolding = [], '/analyst-summary-rating': getAnalystSummary = {},
'/etf-sector-weighting': getIndexSectorWeighting = [], '/stock-quote': getStockQuote = {},
'/stock-quote': getStockQuote = [], '/pre-post-quote': getPrePostQuote = {},
'/pre-post-quote': getPrePostQuote = [], '/wiim': getWhyPriceMoved = {},
'/wiim': getWhyPriceMoved = [], '/one-day-price': getOneDayPrice = {},
'/one-day-price': getOneDayPrice = [], '/next-earnings': getNextEarnings = {},
'/stock-news': getNews = [] '/earnings-surprise': getEarningsSurprise = {},
} = indexData; '/stock-news': getNews = {}
} = stockData;
return { return {
getIndexProfile, getStockDeck,
getIndexHolding, getAnalystSummary,
getIndexSectorWeighting,
getStockQuote, getStockQuote,
getPrePostQuote, getPrePostQuote,
getWhyPriceMoved, getWhyPriceMoved,
getOneDayPrice, getOneDayPrice,
getNextEarnings,
getEarningsSurprise,
getNews, getNews,
getUserWatchlist: userWatchlist, getUserWatchlist: userWatchlist,
companyName: cleanString(getIndexProfile?.at(0)?.name), companyName: cleanString(getStockDeck?.companyName),
getParams: tickerID getParams: tickerID
}; };
} catch (error) { } catch (error) {
console.error('Error in load function:', error); return { error: 'Failed to load stock data' };
return getDefaultResponse(tickerID);
} }
}; };