improve: code quality

This commit is contained in:
ryana mittens 2024-09-06 18:24:33 +08:00
parent eff9a06d57
commit 7869362aeb

View file

@ -1,21 +1,23 @@
const SPARKLE_BASE_URL = process.env.NEXT_PUBLIC_SPARKLE_BASE_URL; const SPARKLE_BASE_URL = process.env.NEXT_PUBLIC_SPARKLE_BASE_URL;
const handleResponse = async (res: Response) => {
if (!res.ok) {
const error = await res.json();
throw new Error(error.message || 'An error occurred');
}
return res.json();
};
export const fetchQuote = async (symbol: string) => { export const fetchQuote = async (symbol: string) => {
const url = `${SPARKLE_BASE_URL}/api/v1/quote?symbol=${symbol}`; const url = `${SPARKLE_BASE_URL}/api/v1/quote?symbol=${symbol}`;
const res = await fetch(url); const res = await fetch(url);
if (!res.ok) { return handleResponse(res);
throw new Error('Error fetching quote');
}
return res.json();
}; };
export const fetchSymbols = async (symbol: string) => { export const fetchSymbols = async (symbol: string) => {
const url = `${SPARKLE_BASE_URL}/api/v1/search?query=${symbol}`; const url = `${SPARKLE_BASE_URL}/api/v1/search?query=${symbol}`;
const res = await fetch(url); const res = await fetch(url);
if (!res.ok) { const data = await handleResponse(res);
throw new Error('Error fetching symbols');
}
const data = await res.json();
return { return {
symbols: data.result, symbols: data.result,
totalCount: data.totalCount, totalCount: data.totalCount,
@ -25,26 +27,23 @@ export const fetchSymbols = async (symbol: string) => {
export const startWebSocket = async () => { export const startWebSocket = async () => {
const url = `${SPARKLE_BASE_URL}/ws/start-websocket`; const url = `${SPARKLE_BASE_URL}/ws/start-websocket`;
const res = await fetch(url); const res = await fetch(url);
if (!res.ok) { return handleResponse(res);
throw new Error('Error starting WebSocket');
}
return res.json();
}; };
export const fetchNews = async () => { export const fetchNews = async () => {
const url = `${SPARKLE_BASE_URL}/api/v1/marketnews`; const url = `${SPARKLE_BASE_URL}/api/v1/marketnews`;
const res = await fetch(url); const res = await fetch(url);
if (!res.ok) { return handleResponse(res);
throw new Error('Error fetching news'); };
}
return res.json();
}
export const fetchProfile = async (symbol: string) => { export const fetchProfile = async (symbol: string) => {
const url = `${SPARKLE_BASE_URL}/api/v1/profile?symbol=${symbol}`; const url = `${SPARKLE_BASE_URL}/api/v1/profile?symbol=${symbol}`;
const res = await fetch(url); const res = await fetch(url);
if (!res.ok) { return handleResponse(res);
throw new Error('Error fetching profile');
}
return res.json();
}; };
export const fetchPeers = async (symbol: string) => {
const url = `${SPARKLE_BASE_URL}/api/v1/peers?symbol=${symbol}`;
const res = await fetch(url);
return handleResponse(res);
};