From 7869362aeb108017b55fa86e6970b1bea19f0379 Mon Sep 17 00:00:00 2001 From: Ryana May Que Date: Fri, 6 Sep 2024 18:24:33 +0800 Subject: [PATCH] improve: code quality --- src/utils/sparkle.ts | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/src/utils/sparkle.ts b/src/utils/sparkle.ts index de6a242..6df38be 100644 --- a/src/utils/sparkle.ts +++ b/src/utils/sparkle.ts @@ -1,21 +1,23 @@ 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) => { const url = `${SPARKLE_BASE_URL}/api/v1/quote?symbol=${symbol}`; const res = await fetch(url); - if (!res.ok) { - throw new Error('Error fetching quote'); - } - return res.json(); + return handleResponse(res); }; export const fetchSymbols = async (symbol: string) => { const url = `${SPARKLE_BASE_URL}/api/v1/search?query=${symbol}`; const res = await fetch(url); - if (!res.ok) { - throw new Error('Error fetching symbols'); - } - const data = await res.json(); + const data = await handleResponse(res); return { symbols: data.result, totalCount: data.totalCount, @@ -25,26 +27,23 @@ export const fetchSymbols = async (symbol: string) => { export const startWebSocket = async () => { const url = `${SPARKLE_BASE_URL}/ws/start-websocket`; const res = await fetch(url); - if (!res.ok) { - throw new Error('Error starting WebSocket'); - } - return res.json(); + return handleResponse(res); }; export const fetchNews = async () => { const url = `${SPARKLE_BASE_URL}/api/v1/marketnews`; const res = await fetch(url); - if (!res.ok) { - throw new Error('Error fetching news'); - } - return res.json(); -} + return handleResponse(res); +}; export const fetchProfile = async (symbol: string) => { const url = `${SPARKLE_BASE_URL}/api/v1/profile?symbol=${symbol}`; const res = await fetch(url); - if (!res.ok) { - throw new Error('Error fetching profile'); - } - return res.json(); + return handleResponse(res); }; + +export const fetchPeers = async (symbol: string) => { + const url = `${SPARKLE_BASE_URL}/api/v1/peers?symbol=${symbol}`; + const res = await fetch(url); + return handleResponse(res); +}; \ No newline at end of file