optimize code

This commit is contained in:
MuslemRahimi 2024-07-27 01:28:13 +02:00
parent f54cc2f355
commit e8b80ad436
2 changed files with 56 additions and 146 deletions

View File

@ -44,7 +44,6 @@
export let data; export let data;
let cloudFrontUrl = import.meta.env.VITE_IMAGE_URL; let cloudFrontUrl = import.meta.env.VITE_IMAGE_URL;
console.log(cloudFrontUrl)
//const trialLeftDays = Math?.floor(addDays(data, 7, '')); //const trialLeftDays = Math?.floor(addDays(data, 7, ''));

View File

@ -1,159 +1,73 @@
const cleanString = (input) => {
let companyName; const substringsToRemove = [
'Depositary', 'Inc.', 'Incorporated', 'Holdings', 'Corporation', 'Corporations',
function cleanString(input) { 'LLC', 'Holdings plc American Depositary Shares', 'Holding Corporation', 'Oyj',
// Define a list of substrings to remove (case insensitive) 'Company', 'The', 'plc',
const substringsToRemove = [ ];
'Depositary', const pattern = new RegExp(`\\b(${substringsToRemove.join('|')})\\b|,`, 'gi');
'Inc.', return input?.replace(pattern, '').trim();
'Incorporated',
'Holdings',
'Corporation',
'Corporations',
'LLC',
'Holdings plc American Depositary Shares',
'Holding Corporation',
'Oyj',
'Company',
'The',
'plc',
];
// Create a regular expression pattern that matches any of the substrings surrounded by word boundaries
const pattern = new RegExp(`\\b(${substringsToRemove?.join('|')})\\b|,`, 'gi');
// Use the replace method to remove the specified substrings and commas, then trim the result
return input?.replace(pattern, '')?.trim();
}
const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
const postData = {
ticker: ticker
};
const response = await fetch(apiURL + endpoint, {
method: 'POST',
headers: {
"Content-Type": "application/json", "X-API-KEY": apiKey
},
body: JSON.stringify(postData)
});
const output = await response?.json();
if(endpoint === '/stockdeck')
{
companyName = cleanString(output?.at(0)?.companyName);
}
return output;
}; };
const fetchWatchlist = async (fastifyURL, userId) => { const fetchData = async (apiURL, apiKey, endpoint, ticker) => {
const response = await fetch(`${apiURL}${endpoint}`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-API-KEY": apiKey
},
body: JSON.stringify({ ticker })
});
return response.json();
};
const postData = {'userId': userId} const fetchFromFastify = async (fastifyURL, endpoint, userId) => {
const response = await fetch(fastifyURL+'/all-watchlists', { const response = await fetch(`${fastifyURL}${endpoint}`, {
method: 'POST', method: 'POST',
headers: { headers: { "Content-Type": "application/json" },
"Content-Type": "application/json" body: JSON.stringify({ userId })
}, });
body: JSON.stringify(postData) const { items } = await response.json();
}); return items;
};
const fetchCommunitySentiment = async (pb, ticker, cookies) => {
const output = (await response?.json())?.items; const cookieVote = cookies.get(`community-sentiment-${ticker}`);
return output; const today = new Date().toISOString().split('T')[0];
} const tomorrow = new Date(new Date().setDate(new Date().getDate() + 1)).toISOString().split('T')[0];
async function fetchPortfolio(fastifyURL, userId)
{
const postData = {'userId': userId};
const response = await fetch(fastifyURL+'/get-portfolio-data', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(postData)
});
const output = (await response?.json())?.items;
return output
}
async function fetchCommunitySentiment(pb, ticker, cookies)
{
let alreadyVoted;
const cookieVote = cookies?.get('community-sentiment-'+ticker);
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
const startDate = today.toISOString().split('T')[0];
const endDate = tomorrow.toISOString().split('T')[0];
const output = await pb.collection("sentiment").getFullList({ const output = await pb.collection("sentiment").getFullList({
filter: `ticker="${ticker}" && created >= "${startDate}" && created < "${endDate}"` filter: `ticker="${ticker}" && created >= "${today}" && created < "${tomorrow}"`
}); });
if (cookieVote) { return {
alreadyVoted = cookieVote; alreadyVoted: cookieVote || null,
} sentimentData: output[0] || {}
};
};
if(output?.length !== 0) { export const load = async ({ params, locals, cookies, setHeaders }) => {
const { apiURL, fastifyURL, apiKey, pb, user } = locals;
return {'alreadyVoted': alreadyVoted, 'sentimentData': output?.at(0)} const { tickerID } = params;
}
else {
return {'alreadyVoted': alreadyVoted, 'sentimentData': {} }
}
} const endpoints = [
'/similar-stocks', '/stockdeck', '/analyst-summary-rating', '/stock-quote',
'/bull-bear-say', '/wiim', '/top-etf-ticker-holder', '/one-day-price'
];
export const load = async ({ params, locals, cookies, setHeaders}) => { const promises = [
...endpoints.map(endpoint => fetchData(apiURL, apiKey, endpoint, tickerID)),
let apiURL = locals?.apiURL; fetchFromFastify(fastifyURL, '/all-watchlists', user?.id),
let fastifyURL = locals?.fastifyURL; fetchFromFastify(fastifyURL, '/get-portfolio-data', user?.id),
let apiKey = locals?.apiKey; fetchCommunitySentiment(pb, tickerID, cookies)
let wsURL = locals?.wsURL;
const promises = [
fetchData(apiURL,apiKey, '/similar-stocks',params.tickerID),
fetchData(apiURL,apiKey, '/stockdeck',params.tickerID),
fetchData(apiURL,apiKey, '/analyst-summary-rating',params.tickerID),
fetchData(apiURL,apiKey, '/stock-quote',params.tickerID),
fetchData(apiURL,apiKey, '/bull-bear-say',params.tickerID),
fetchData(apiURL,apiKey, '/wiim',params.tickerID),
fetchData(apiURL,apiKey, '/top-etf-ticker-holder',params.tickerID),
fetchData(apiURL,apiKey, '/one-day-price',params.tickerID),
fetchWatchlist(fastifyURL, locals?.user?.id),
fetchPortfolio(fastifyURL, locals?.user?.id),
fetchCommunitySentiment(locals?.pb, params.tickerID, cookies)
]; ];
const [ const [
getSimilarStock, getSimilarStock, getStockDeck, getAnalystRating, getStockQuote,
getStockDeck, getBullBearSay, getWhyPriceMoved, getTopETFHolder, getOneDayPrice,
getAnalystRating, getUserWatchlist, getUserPortfolio, getCommunitySentiment
getStockQuote,
getBullBearSay,
getWhyPriceMoved,
getTopETFHolder,
getOneDayPrice,
getUserWatchlist,
getUserPortfolio,
getCommunitySentiment,
] = await Promise.all(promises); ] = await Promise.all(promises);
setHeaders({ 'cache-control': 'public, max-age=300' });
setHeaders({
'cache-control': 'public, max-age=300' //Cache data for 5 min
});
return { return {
getSimilarStock, getSimilarStock,
@ -167,9 +81,6 @@ export const load = async ({ params, locals, cookies, setHeaders}) => {
getUserWatchlist, getUserWatchlist,
getUserPortfolio, getUserPortfolio,
getCommunitySentiment, getCommunitySentiment,
companyName, companyName: cleanString(getStockDeck?.[0]?.companyName),
wsURL,
}; };
};
};