/**
* @file
* File : apiSlice.js\
* It is used by RTK Query \
* Defines Base query using axios instance
*
* @author Pierre-Yves Léglise <contact@axialdata.net>
* @name apiSlice
*/
import { createApi } from '@reduxjs/toolkit/query/react'
import axiosInstance from './axios'
import { setAppError } from '../appSlice'
import store from '../store'
/**
* Base query function for RTK Query using Axios.
* Handles requests, error processing, and dispatches error state.
*
* @category ApiSlice
* @function
* @author Pierre-Yves Léglise <contact@axialdata.net>
* @param {Object} params - Parameters for the Axios request.
* @param {string} params.url - The URL of the request.
* @param {string} [params.method='GET'] - The HTTP method (default is 'GET').
* @param {Object} [params.data] - The data to send with the request.
* @param {Object} [params.params] - The query parameters for the request.
* @param {Object} [params.headers] - The headers for the request.
* @param {string} [params.responseType] - The type of data to expect in response.
* @example
* const result = await axiosBaseQuery({
* url: '/api/endpoint',
* method: 'POST',
* data: {
* key: 'value',
* },
* params: {
* param1: 'value1',
* },
* headers: {
* 'Content-Type': 'application/json',
* },
* responseType: 'json',
* })
* @returns {Promise<Object>} The result of the request or an error object.
*/
const axiosBaseQuery =
() =>
async ({ url, method, data, params, headers, responseType }) => {
// const xsrfToken = sessionStorage.xsrfToken
try {
const result = await axiosInstance({
url: url,
method,
data,
params,
headers,
withCredentials: true,
crossDomain: true,
responseType,
xsrfCookieName: 'csrf',
})
store.dispatch(setAppError(''))
return { data: result.data }
} catch (axiosError) {
let err = axiosError
!err.response?.data.message &&
store.dispatch(setAppError(err.response?.data.message || err?.message))
return {
error: {
status: err.response?.status,
data: err.response?.data || err,
},
}
}
}
/**
* RTK Query API slice configuration.
* Uses base query defined by `axiosBaseQuery` and initializes endpoints.
*
* @author Pierre-Yves Léglise <contact@axialdata.net>
* @constant {Object} apiSlice
* @property {Function} baseQuery - Base query function for making API requests.
* @property {Function} endpoints - Function to define API endpoints.
* @example
* const { useGetUsersQuery } = apiSlice
* @returns {Object} The RTK Query API slice configuration.
*/
export const apiSlice = createApi({
baseQuery: axiosBaseQuery(),
tagTypes: ['Orders', 'Invoices', 'OrdersGroups'],
endpoints: (builder) => ({}),
})