chore: refactoring and fixes for getfetchclient

This commit is contained in:
Bassel Kanso 2024-04-23 10:07:14 +03:00
parent 403e00ab42
commit 7899cd5db8
2 changed files with 36 additions and 20 deletions

View File

@ -100,11 +100,11 @@ type FetchClient = {
*/ */
const getFetchClient = (defaultOptions: FetchConfig = {}): FetchClient => { const getFetchClient = (defaultOptions: FetchConfig = {}): FetchClient => {
const backendURL = window.strapi.backendURL; const backendURL = window.strapi.backendURL;
const headers = new Headers({ const defaultHeader = {
Accept: 'application/json', Accept: 'application/json',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Authorization: `Bearer ${getToken()}`, Authorization: `Bearer ${getToken()}`,
}); };
const addPrependingSlash = (url: string) => (url.charAt(0) !== '/' ? `/${url}` : url); const addPrependingSlash = (url: string) => (url.charAt(0) !== '/' ? `/${url}` : url);
@ -117,21 +117,18 @@ const getFetchClient = (defaultOptions: FetchConfig = {}): FetchClient => {
// Add a response interceptor to return the response // Add a response interceptor to return the response
const responseInterceptor = async <TData>(response: Response): Promise<FetchResponse<TData>> => { const responseInterceptor = async <TData>(response: Response): Promise<FetchResponse<TData>> => {
try { try {
console.log('response ===> ', response);
const result = await response.json(); const result = await response.json();
console.log('result ===>', result);
if (!response.ok && result.error) { if (!response.ok && result.error) {
throw new FetchError(result.error.message, { data: result } as any); throw new FetchError(result.error.message, { data: result } as any);
} }
if (!response.ok) { if (!response.ok) {
throw new FetchError('Unknown Server Error'); throw new FetchError('Unknown Server Error');
} }
return { return { data: result };
data: result,
};
} catch (error) { } catch (error) {
if (error instanceof SyntaxError && response.ok) { if (error instanceof SyntaxError && response.ok) {
// You can assign a default value to result or handle the error in another way // Making sure that a SyntaxError doesn't throw if it's successful
return { data: [], status: response.status }; return { data: [], status: response.status };
} else { } else {
throw error; throw error;
@ -162,6 +159,10 @@ const getFetchClient = (defaultOptions: FetchConfig = {}): FetchClient => {
const fetchClient: FetchClient = { const fetchClient: FetchClient = {
get: async <TData>(url: string, options?: FetchOptions): Promise<FetchResponse<TData>> => { get: async <TData>(url: string, options?: FetchOptions): Promise<FetchResponse<TData>> => {
const headers = new Headers({
...defaultHeader,
...options?.headers,
});
/** /**
* this applies all our transformations to the URL * this applies all our transformations to the URL
* - normalizing (making sure it has the correct slash) * - normalizing (making sure it has the correct slash)
@ -181,12 +182,18 @@ const getFetchClient = (defaultOptions: FetchConfig = {}): FetchClient => {
data?: TSend, data?: TSend,
options?: FetchOptions options?: FetchOptions
): Promise<FetchResponse<TData>> => { ): Promise<FetchResponse<TData>> => {
const headers = new Headers({
...defaultHeader,
...options?.headers,
});
const createRequestUrl = makeCreateRequestUrl(options); const createRequestUrl = makeCreateRequestUrl(options);
const response = await fetch(createRequestUrl(url), { const response = await fetch(createRequestUrl(url), {
signal: options?.signal ?? defaultOptions.signal, signal: options?.signal ?? defaultOptions.signal,
method: 'POST', method: 'POST',
headers, headers,
body: JSON.stringify(data), body: options?.headers?.['Content-Type'].includes('multipart/form-data')
? data
: JSON.stringify(data),
}); });
return responseInterceptor<TData>(response); return responseInterceptor<TData>(response);
}, },
@ -195,12 +202,19 @@ const getFetchClient = (defaultOptions: FetchConfig = {}): FetchClient => {
data?: TSend, data?: TSend,
options?: FetchOptions options?: FetchOptions
): Promise<FetchResponse<TData>> => { ): Promise<FetchResponse<TData>> => {
const headers = new Headers({
...defaultHeader,
...options?.headers,
});
const createRequestUrl = makeCreateRequestUrl(options); const createRequestUrl = makeCreateRequestUrl(options);
const response = await fetch(createRequestUrl(url), { const response = await fetch(createRequestUrl(url), {
signal: options?.signal ?? defaultOptions.signal, signal: options?.signal ?? defaultOptions.signal,
method: 'PUT', method: 'PUT',
headers, headers,
body: JSON.stringify(data), body: options?.headers?.['Content-Type'].includes('multipart/form-data')
? data
: JSON.stringify(data),
}); });
return responseInterceptor<TData>(response); return responseInterceptor<TData>(response);
@ -209,6 +223,11 @@ const getFetchClient = (defaultOptions: FetchConfig = {}): FetchClient => {
url: string, url: string,
options?: FetchOptions options?: FetchOptions
): Promise<R> => { ): Promise<R> => {
const headers = new Headers({
...defaultHeader,
...options?.headers,
});
const createRequestUrl = makeCreateRequestUrl(options); const createRequestUrl = makeCreateRequestUrl(options);
const response = await fetch(createRequestUrl(url), { const response = await fetch(createRequestUrl(url), {
signal: options?.signal ?? defaultOptions.signal, signal: options?.signal ?? defaultOptions.signal,

View File

@ -1,9 +1,4 @@
import { import { getFetchClient, type FetchOptions, type FetchError } from '@strapi/admin/strapi-admin';
getFetchClient,
type FetchResponse,
type FetchOptions,
type FetchError,
} from '@strapi/admin/strapi-admin';
export interface QueryArguments<TSend> { export interface QueryArguments<TSend> {
url: string; url: string;
@ -22,26 +17,28 @@ const fetchBaseQuery = async <TData = unknown, TSend = unknown>({
const { get, post, del, put } = getFetchClient(); const { get, post, del, put } = getFetchClient();
if (method === 'POST') { if (method === 'POST') {
const result = await post<TData, FetchResponse<TData>, TSend>(url, data, config); const result = await post<TData, TSend>(url, data, config);
return { data: result.data }; return { data: result.data };
} }
if (method === 'DELETE') { if (method === 'DELETE') {
const result = await del<TData, FetchResponse<TData>>(url, config); const result = await del<TData>(url, config);
return { data: result.data }; return { data: result.data };
} }
if (method === 'PUT') { if (method === 'PUT') {
const result = await put<TData, FetchResponse<TData>, TSend>(url, data, config); const result = await put<TData>(url, data, config);
return { data: result.data }; return { data: result.data };
} }
/** /**
* Default is GET. * Default is GET.
*/ */
const result = await get<TData, FetchResponse<TData>>(url, config); const result = await get<TData>(url, config);
console.log('baseQuery', result);
return { data: result.data }; return { data: result.data };
} catch (error) { } catch (error) {
console.log('did we arrive here for some reason ?');
const err = error as FetchError; const err = error as FetchError;
/** /**
* Handle error of type FetchError * Handle error of type FetchError