@@ -5,6 +5,7 @@ export enum FetchType {
5
5
DELETE = "DELETE" ,
6
6
}
7
7
8
+ // error logic faulty => does both, error & not error if both are provided
8
9
export function jsonFetchWrapper ( url : string , fetchType : FetchType , onResult ?: ( result : any ) => void , body ?: BodyInit , headers ?: any , onError ?: ( response : any ) => void ) {
9
10
if ( ! headers ) headers = { } ;
10
11
headers [ "Content-Type" ] = "application/json" ;
@@ -30,6 +31,24 @@ export function jsonFetchWrapper(url: string, fetchType: FetchType, onResult?: (
30
31
31
32
}
32
33
34
+ //runs either onError or onResult, not both
35
+ export function jsonFetchWrapperEitherOr ( url : string , fetchType : FetchType , onResult ?: ( result : any ) => void , body ?: BodyInit , headers ?: any , onError ?: ( response : any ) => void ) {
36
+ if ( ! headers ) headers = { } ;
37
+ headers [ "Content-Type" ] = "application/json" ;
38
+
39
+ const finalOnError = onError ? onError : ( ( response : any ) => { throw new Error ( "Error in request at " + url ) } ) ;
40
+ fetch ( url , {
41
+ method : fetchType ,
42
+ headers : headers ,
43
+ body : body ,
44
+ } ) . then ( response => {
45
+ if ( ! response . ok ) return response . text ( ) . then ( ( text ) => finalOnError ( text ) ) ;
46
+ else return response . json ( ) . then ( ( json ) => onResult ( json ) ) ;
47
+ } , ( error ) => {
48
+ console . log ( "Error in request at " + url ) ;
49
+ } ) ;
50
+ }
51
+
33
52
export function textFetchWrapper ( url : string , fetchType : FetchType , onResult ?: ( result : any ) => void , body ?: BodyInit , headers ?: any ) {
34
53
if ( ! headers ) headers = { } ;
35
54
headers [ "Content-Type" ] = "application/json" ;
0 commit comments