import { errorResponse } from "@/core/utils/errorResponse"; import { successRequest } from "@/core/utils/successRequest"; import axios from "axios"; import { useAuth } from "../contexts/auth"; import { useSidebarBadge } from "./useSidebarBadge"; const defaultOptions = { data: {}, requestOptions: { headers: {}, }, notificationShow: true, notificationSuccess: false, notificationFailed: true, hasSidebarUpdate: false, }; const useRequest = (initOptions) => { const { mutate: sidebarUpdate } = useSidebarBadge(); const { logout } = useAuth(); const _options = Object.assign({}, defaultOptions, initOptions); /** * Performs an HTTP request. * @param {string} url - The URL to send the request to. * @param {'get' | 'post' | 'put' | 'delete'} [method='get'] - HTTP method. * @param {object} [options] - Additional request options. * @returns {Promise} - Axios response. */ return async (url = "", method = "get", options) => { const mergedOptions = Object.assign({}, _options, options); try { const response = await axios({ url, method, data: method === "get" ? null : mergedOptions.data, withCredentials: true, ...mergedOptions.requestOptions, }); if (mergedOptions.hasSidebarUpdate) { if (method === "post" || method === "put" || method === "delete") sidebarUpdate(); } successRequest(mergedOptions.notificationShow && mergedOptions.notificationSuccess, "request_data"); return response; } catch (error) { if (error.response) { errorResponse( error.response, mergedOptions.notificationShow && mergedOptions.notificationFailed, "request_data", logout ); } throw error; } }; }; export default useRequest;