diff --git a/src/service/api.tsx b/src/service/api.tsx index 20f55e5..2be430e 100644 --- a/src/service/api.tsx +++ b/src/service/api.tsx @@ -59,54 +59,67 @@ const nonToastableCalls: string[] = [ serviiRequest.fetchPlayersStatus, ]; +function toast_status(status: number, message: string) { + let toastType: 'success' | 'error' | 'info' | 'warning'; + + if (status >= 200 && status < 300) { + toastType = 'success'; + } else if (status >= 400 && status < 600) { + toastType = 'error'; + } else { + toastType = 'info'; + } + if (status == 666) { + toastType = 'warning'; + } + + toast[toastType](message, { + position: "top-right", + autoClose: 3500, + hideProgressBar: false, + closeOnClick: true, + pauseOnHover: true, + draggable: true, + progress: undefined, + theme: "light", + transition: Bounce, + }); +} + class serviiApi { - constructor() {} - private static async call(endpoint: serviiRequest, body: T): Promise { - const response = await fetch(`${apiUrl}/${endpoint}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(body), - }); - const status: number = response.status; - const json = await response.json(); - - if (json.message === undefined) { - if (!(endpoint === serviiRequest.fetchServers)) { - return { return_code: status, message: "Couldn't find an available API" }; - } - return { return_code: status, message: json }; - } - - if (!nonToastableCalls.includes(endpoint)) { - - let toastType: 'success' | 'error' | 'info'; - - if (status >= 200 && status < 300) { - toastType = 'success'; - } else if (status >= 400 && status < 600) { - toastType = 'error'; - } else { - toastType = 'info'; - } - - toast[toastType](json.message, { - position: "top-right", - autoClose: 3500, - hideProgressBar: false, - closeOnClick: true, - pauseOnHover: true, - draggable: true, - progress: undefined, - theme: "light", - transition: Bounce, + const unreachable: string = "Couldn't find an available API"; + try { + const response = await fetch(`${apiUrl}/${endpoint}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body), }); + const status: number = response.status; + const json = await response.json(); + const message = json.message; + + if (message === undefined) { + if (!(endpoint === serviiRequest.fetchServers)) { + return {return_code: 503, message: "Couldn't find an available API"}; + } + return {return_code: status, message: json}; + } + + if (!nonToastableCalls.includes(endpoint)) { + toast_status(status, message); + } + + return {return_code: status, message: json.message}; + } catch (error) { + toast_status(666, unreachable); + return {return_code: 503, message: "Couldn't find an available API"} + } } - return { return_code: status, message: json.message }; - } + constructor() {} private static token(): string { const currentUser = getAuth().currentUser;