Address pr comments

This commit is contained in:
Jasneet Singh committed 2025-01-09 17:38:08 -05:00
1 parent 4398010a9f
commit 74f23c1792
1 file changed
+17 -26
+17 -26
View File
@@ -1,20 +1,16 @@
import { toast } from 'react-toastify';
import axios from "axios";
const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;
const FALLBACK_BASE_URL = "http://localhost:5000/api/v1";
import { clearAuthState } from "../Features/Auth/authSlice";
import { clearUptimeMonitorState } from "../Features/UptimeMonitors/uptimeMonitorsSlice";
import { createToast } from "./toastUtils";
class NetworkService {
constructor(store, dispatch, navigate) {
this.store = store;
this.dispatch = dispatch;
this.navigate = navigate;
let baseURL = BASE_URL;
this.lastToastTimestamp = 0;
this.errorOccurred = false;
this.user = this.store.getState().auth?.user;
this.isAdmin = (this.user?.role?.includes("admin") ?? false) || (this.user?.role?.includes("superadmin") ?? false);
this.axiosInstance = axios.create();
this.setBaseUrl(baseURL);
this.unsubscribe = store.subscribe(() => {
@@ -27,15 +23,9 @@ class NetworkService {
baseURL = FALLBACK_BASE_URL;
}
this.setBaseUrl(baseURL);
});
});
this.axiosInstance.interceptors.response.use(
(response) => {
if (this.isAdmin && this.errorOccurred && response.status >= 200 && response.status < 300) {
this.debounceToast("Checkmate server is running properly.", "success");
this.errorOccurred = false;// Reset error flag if a successful response is received after errors
}
return response;
},
(response) => response,
(error) => {
this.handleError(error);
return Promise.reject(error);
@@ -54,22 +44,23 @@ class NetworkService {
this.dispatch(clearAuthState());
this.dispatch(clearUptimeMonitorState());
this.navigate("/login");
} else if (this.isAdmin && status >= 500) {
this.debounceToast("Checkmate server is not running or has issues. Please check.", "error");
this.errorOccurred = true;
} else if (status >= 500) {
// Display toast for server errors to all users
createToast({
variant: "error",
body: "Checkmate server is not running or has issues. Please check.",
});
}
}
}
debounceToast(message, type, debounceDuration = 5000) {
const now = Date.now();
if (now - this.lastToastTimestamp > debounceDuration) {
this.lastToastTimestamp = now;
type === "success" ? toast.success(message) : toast.error(message);
} else if (error.request) {
// Show a toast informing the user the server didn't respond
createToast({
variant: "error",
body: "The server did not respond. Please check your network or try again later.",
});
}
}
cleanup() {
if (this.unsubscribe) {
this.unsubscribe();