11import PostRobot from 'post-robot' ;
2- import axios , { AxiosRequestConfig , AxiosResponse } from 'axios' ;
3- import { onError , convertHeaders , convertAxiosHeadersToHeadersInit } from './utils' ;
2+ import { AxiosRequestConfig , AxiosResponse } from 'axios' ;
3+ import { onError , fetchToAxiosConfig } from './utils' ;
44
55/**
66 * Dispatches a request using PostRobot.
@@ -20,34 +20,28 @@ export const dispatchAdapter = (postRobot: typeof PostRobot) => (config: AxiosRe
2020 * @param options - Optional request options.
2121 * @returns A promise that resolves to a partial Response object.
2222 */
23- export const dispatchApiRequest = async ( url : string , options ?: RequestInit ) : Promise < Partial < Response > > => {
23+ export const dispatchApiRequest = async ( url : string , options ?: RequestInit ) : Promise < Response > => {
2424 try {
25- const config : AxiosRequestConfig = {
26- url,
27- method : options ?. method || "GET" ,
28- ...( options ?. headers && { headers : convertHeaders ( options . headers ) } ) ,
29- ...( options ?. body && { data : options ?. body } )
30- } ;
31-
25+ const config = fetchToAxiosConfig ( url , options ) ;
3226 const responseData = await dispatchAdapter ( PostRobot ) ( config ) as AxiosResponse ;
33- const isCallSuccessful = responseData . status >= 200 && responseData . status < 300 ;
34- const fetchResponse : Partial < Response > = {
35- ok : isCallSuccessful ,
27+ return new Response ( responseData . data , {
3628 status : responseData . status ,
3729 statusText : responseData . statusText ,
38- headers : new Headers ( convertAxiosHeadersToHeadersInit ( responseData . config . headers || { } ) ) ,
39- json : async ( ) => responseData . data ,
40- text : async ( ) => JSON . stringify ( responseData . data ) ,
41- } ;
30+ headers : new Headers ( responseData . config . headers || { } ) ,
31+ } ) ;
4232
43- return fetchResponse ;
44- } catch ( error ) {
45- if ( axios . isAxiosError ( error ) ) {
46- console . error ( "API request failed:" , error . message ) ;
47- throw new Error ( `API request failed: ${ error . message } ` ) ;
33+ } catch ( error : any ) {
34+ if ( error . response ) {
35+ const fetchResponse = new Response ( error . response . data , {
36+ status : error . response . status ,
37+ statusText : error . response . statusText ,
38+ headers : new Headers ( error . response . headers )
39+ } ) ;
40+ return Promise . reject ( fetchResponse ) ;
41+ } else if ( error . request ) {
42+ return Promise . reject ( new Response ( null , { status : 0 , statusText : 'Network Error' } ) ) ;
4843 } else {
49- console . error ( "An unexpected error occurred:" , error ) ;
50- throw new Error ( "An unexpected error occurred" ) ;
44+ return Promise . reject ( new Response ( null , { status : 0 , statusText : error . message } ) ) ;
5145 }
5246 }
5347} ;
0 commit comments