Skip to content

Commit 8337304

Browse files
committed
Adds new json fetch for either error or json
1 parent bda7bcd commit 8337304

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

basic-fetch.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ export enum FetchType {
55
DELETE = "DELETE",
66
}
77

8+
// error logic faulty => does both, error & not error if both are provided
89
export function jsonFetchWrapper(url: string, fetchType: FetchType, onResult?: (result: any) => void, body?: BodyInit, headers?: any, onError?: (response: any) => void) {
910
if (!headers) headers = {};
1011
headers["Content-Type"] = "application/json";
@@ -30,6 +31,24 @@ export function jsonFetchWrapper(url: string, fetchType: FetchType, onResult?: (
3031

3132
}
3233

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+
3352
export function textFetchWrapper(url: string, fetchType: FetchType, onResult?: (result: any) => void, body?: BodyInit, headers?: any) {
3453
if (!headers) headers = {};
3554
headers["Content-Type"] = "application/json";

0 commit comments

Comments
 (0)