refactor the fetchClient to the getFetchClient utils

This commit is contained in:
Simone Taeggi 2022-11-15 12:48:32 +01:00
parent 4da811c322
commit d8a449e2ed
11 changed files with 62 additions and 65 deletions

View File

@ -22,7 +22,7 @@ import {
import injectionZones from './injectionZones'; import injectionZones from './injectionZones';
import favicon from './favicon.png'; import favicon from './favicon.png';
import localStorageKey from './components/LanguageProvider/utils/localStorageKey'; import localStorageKey from './components/LanguageProvider/utils/localStorageKey';
import { fetchClient } from './utils'; import { getFetchClient } from './utils';
class StrapiApp { class StrapiApp {
constructor({ adminConfig, appPlugins, library, middlewares, reducers }) { constructor({ adminConfig, appPlugins, library, middlewares, reducers }) {
@ -452,7 +452,7 @@ class StrapiApp {
showTutorials={this.configurations.tutorials} showTutorials={this.configurations.tutorials}
showReleaseNotification={this.configurations.notifications.releases} showReleaseNotification={this.configurations.notifications.releases}
store={store} store={store}
fetchClient={fetchClient} getFetchClient={getFetchClient}
> >
<> <>
<Helmet <Helmet

View File

@ -21,7 +21,7 @@ describe('ADMIN | COMPONENTS | PluginsInitializer', () => {
runHookSeries={jest.fn()} runHookSeries={jest.fn()}
menu={[]} menu={[]}
settings={{}} settings={{}}
fetchClient={{}} getFetchClient={jest.fn()}
> >
<PluginsInitializer /> <PluginsInitializer />
</StrapiAppProvider> </StrapiAppProvider>

View File

@ -42,7 +42,7 @@ const Providers = ({
showTutorials, showTutorials,
store, store,
themes, themes,
fetchClient, getFetchClient,
}) => { }) => {
return ( return (
<ThemeToggleProvider themes={themes}> <ThemeToggleProvider themes={themes}>
@ -64,7 +64,7 @@ const Providers = ({
runHookWaterfall={runHookWaterfall} runHookWaterfall={runHookWaterfall}
runHookSeries={runHookSeries} runHookSeries={runHookSeries}
settings={settings} settings={settings}
fetchClient={fetchClient} getFetchClient={getFetchClient}
> >
<LibraryProvider components={components} fields={fields}> <LibraryProvider components={components} fields={fields}>
<CustomFieldsProvider customFields={customFields}> <CustomFieldsProvider customFields={customFields}>
@ -147,7 +147,7 @@ Providers.propTypes = {
}).isRequired, }).isRequired,
custom: PropTypes.object, custom: PropTypes.object,
}).isRequired, }).isRequired,
fetchClient: PropTypes.object.isRequired, getFetchClient: PropTypes.func.isRequired,
}; };
export default Providers; export default Providers;

View File

@ -43,7 +43,7 @@ const makeApp = (history, settings) => (
runHookWaterfall={jest.fn()} runHookWaterfall={jest.fn()}
runHookSeries={jest.fn()} runHookSeries={jest.fn()}
menu={[]} menu={[]}
fetchClient={{}} getFetchClient={jest.fn()}
> >
<Router history={history}> <Router history={history}>
<Route path="/settings/:settingId" component={SettingsPage} /> <Route path="/settings/:settingId" component={SettingsPage} />

View File

@ -1,48 +0,0 @@
import axios from 'axios';
import { auth } from '@strapi/helper-plugin';
function getFetchClient() {
const instance = axios.create({
baseURL: process.env.STRAPI_ADMIN_BACKEND_URL,
});
instance.interceptors.request.use(
async (config) => {
config.headers = {
Authorization: `Bearer ${auth.getToken()}`,
Accept: 'application/json',
'Content-Type': 'application/json',
};
return config;
},
(error) => {
Promise.reject(error);
}
);
instance.interceptors.response.use(
(response) => response,
(error) => {
// whatever you want to do with the error
if (error?.response?.status === 401) {
auth.clearAppStorage();
window.location.reload();
}
throw error;
}
);
return instance;
}
const instance = getFetchClient();
export default {
get: instance.get,
put: instance.put,
post: instance.post,
delete: instance.delete,
getFetchClient,
};

View File

@ -0,0 +1,45 @@
import axios from 'axios';
import { auth } from '@strapi/helper-plugin';
const instance = axios.create({
baseURL: process.env.STRAPI_ADMIN_BACKEND_URL,
});
instance.interceptors.request.use(
async (config) => {
config.headers = {
Authorization: `Bearer ${auth.getToken()}`,
Accept: 'application/json',
'Content-Type': 'application/json',
};
return config;
},
(error) => {
Promise.reject(error);
}
);
instance.interceptors.response.use(
(response) => response,
(error) => {
// whatever you want to do with the error
if (error?.response?.status === 401) {
auth.clearAppStorage();
window.location.reload();
}
throw error;
}
);
const getFetchClient = () => {
return {
get: (url, config) => instance.get(url, config),
put: (url, data, config) => instance.put(url, data, config),
post: (url, data, config) => instance.post(url, data, config),
delete: (url, config) => instance.get(url, config),
};
};
export default getFetchClient;

View File

@ -7,4 +7,4 @@ export { default as sortLinks } from './sortLinks';
export { default as getExistingActions } from './getExistingActions'; export { default as getExistingActions } from './getExistingActions';
export { default as getRequestUrl } from './getRequestUrl'; export { default as getRequestUrl } from './getRequestUrl';
export { default as getFullName } from './getFullName'; export { default as getFullName } from './getFullName';
export { default as fetchClient } from './fetchClient'; export { default as getFetchClient } from './getFetchClient';

View File

@ -108,7 +108,7 @@ const DataManagerProvider = ({
{ data: reservedNames }, { data: reservedNames },
] = await Promise.all( ] = await Promise.all(
['components', 'content-types', 'reserved-names'].map((endPoint) => { ['components', 'content-types', 'reserved-names'].map((endPoint) => {
// TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from fetchClient // TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from getFetchClient
return axiosInstance.get(endPoint); return axiosInstance.get(endPoint);
}) })
); );
@ -266,7 +266,7 @@ const DataManagerProvider = ({
if (userConfirm) { if (userConfirm) {
lockAppWithAutoreload(); lockAppWithAutoreload();
// TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from fetchClient // TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from getFetchClient
await axiosInstance.delete(requestURL); await axiosInstance.delete(requestURL);
// Make sure the server has restarted // Make sure the server has restarted
@ -316,7 +316,7 @@ const DataManagerProvider = ({
} }
lockAppWithAutoreload(); lockAppWithAutoreload();
// TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from fetchClient // TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from getFetchClient
await axiosInstance.delete(requestURL); await axiosInstance.delete(requestURL);
// Make sure the server has restarted // Make sure the server has restarted
@ -350,7 +350,7 @@ const DataManagerProvider = ({
lockAppWithAutoreload(); lockAppWithAutoreload();
// Update the category // Update the category
// TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from fetchClient // TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from getFetchClient
await axiosInstance({ url: requestURL, method: 'PUT', data: body }); await axiosInstance({ url: requestURL, method: 'PUT', data: body });
// Make sure the server has restarted // Make sure the server has restarted
@ -508,7 +508,7 @@ const DataManagerProvider = ({
// Lock the app // Lock the app
lockAppWithAutoreload(); lockAppWithAutoreload();
// TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from fetchClient // TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from getFetchClient
await axiosInstance({ await axiosInstance({
url: requestURL, url: requestURL,
method, method,

View File

@ -1,6 +1,6 @@
import axios from 'axios'; import axios from 'axios';
import { auth, wrapAxiosInstance } from '@strapi/helper-plugin'; import { auth, wrapAxiosInstance } from '@strapi/helper-plugin';
// TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from fetchClient // TODO: remember to pass also the pluginId when you use the new get, post, put, delete methods from getFetchClient
import pluginId from '../pluginId'; import pluginId from '../pluginId';
const instance = axios.create({ const instance = axios.create({

View File

@ -2,9 +2,9 @@ import { useContext } from 'react';
import StrapiAppContext from '../../contexts/StrapiAppContext'; import StrapiAppContext from '../../contexts/StrapiAppContext';
const useFetchClient = () => { const useFetchClient = () => {
const { fetchClient } = useContext(StrapiAppContext); const { getFetchClient } = useContext(StrapiAppContext);
return fetchClient; return getFetchClient();
}; };
export default useFetchClient; export default useFetchClient;

View File

@ -31,7 +31,7 @@ StrapiAppProvider.propTypes = {
runHookWaterfall: PropTypes.func.isRequired, runHookWaterfall: PropTypes.func.isRequired,
runHookSeries: PropTypes.func.isRequired, runHookSeries: PropTypes.func.isRequired,
settings: PropTypes.object.isRequired, settings: PropTypes.object.isRequired,
fetchClient: PropTypes.object.isRequired, getFetchClient: PropTypes.func.isRequired,
}; };
export default StrapiAppProvider; export default StrapiAppProvider;