@@ -19,33 +19,29 @@ const getAuthToken = () => {
1919}
2020
2121interface BackendErrorResponse {
22- httpStatus : number
23- messages : string [ ]
24- errorCode : string
22+ status : string
23+ error : string
2524}
2625
2726export class ApiError extends Error {
2827 constructor (
29- public status : number ,
30- public messages ? : string [ ] ,
31- public errorCode ?: string ,
28+ public status : string ,
29+ public error : string ,
30+ public httpCode : number ,
3231 ) {
33- super ( messages ? messages . join ( ', ' ) : status . toString ( ) )
32+ super ( error )
3433 this . name = 'ApiError'
3534 }
3635}
3736
3837export async function apiFetch < T > ( path : string , options ?: RequestInit ) : Promise < T > {
3938 const isFormData = options ?. body instanceof FormData
4039
41- const defaultHeaders : Record < string , string > =
42- options ?. body && ! isFormData ? { 'Content-Type' : 'application/json' } : { }
43-
4440 const headers : Record < string , string > = {
45- ...defaultHeaders ,
46- 'X-Session-ID' : getAnonymousSessionId ( ) ,
4741 ...( options ?. headers as Record < string , string > ) ,
42+ 'X-Session-ID' : getAnonymousSessionId ( ) ,
4843 }
44+ if ( options ?. body && ! isFormData ) headers [ 'Content-Type' ] = 'application/json'
4945
5046 const token = getAuthToken ( )
5147 if ( token ) {
@@ -61,15 +57,11 @@ export async function apiFetch<T>(path: string, options?: RequestInit): Promise<
6157 const contentType = response . headers . get ( 'content-type' )
6258 if ( contentType ?. includes ( 'application/json' ) ) {
6359 const error : BackendErrorResponse = await response . json ( )
64- throw new ApiError ( error . httpStatus , error . messages , error . errorCode )
60+ throw new ApiError ( error . status , error . error , response . status )
6561 }
66- throw new ApiError ( response . status , [ response . statusText ] )
67- }
68-
69- const contentType = response . headers . get ( 'content-type' )
70- if ( contentType ?. includes ( 'application/json' ) ) {
71- return response . json ( )
62+ throw new ApiError ( 'Server Error' , `HTTP ${ response . status } - ${ response . statusText } ` , response . status )
7263 }
7364
74- return undefined as T
65+ // assume the response is in json as our API should always do, errors can be caught with <promise>.catch()
66+ return response . json ( )
7567}
0 commit comments