-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-fetch.ts
More file actions
74 lines (64 loc) · 2.48 KB
/
basic-fetch.ts
File metadata and controls
74 lines (64 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
export enum FetchType {
GET = "GET",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
PATCH = "PATCH"
}
// error logic faulty => does both, error & not error if both are provided
export function jsonFetchWrapper(url: string, fetchType: FetchType, onResult?: (result: any) => void, body?: BodyInit, headers?: any, onError?: (response: any) => void) {
if (!headers) headers = {};
headers["Content-Type"] = "application/json";
let hasError = false;
let myFetch = fetch(url, {
method: fetchType,
headers: headers,
body: body,
}).then(response => {
if (!response.ok) {
if (onError) onError(response);
else throw new Error("Error in request at " + url);
hasError = true;
}
else {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) return response.json();
else return response.text();
}
}, (error) => {
console.log("Error in request at " + url);
});
if (onResult && !hasError) myFetch.then(result => onResult(result));
}
//runs either onError or onResult, not both
export function jsonFetchWrapperEitherOr(url: string, fetchType: FetchType, onResult?: (result: any) => void, body?: BodyInit, headers?: any, onError?: (response: any) => void) {
if (!headers) headers = {};
headers["Content-Type"] = "application/json";
const finalOnError = onError ? onError : ((response: any) => { throw new Error("Error in request at " + url) });
fetch(url, {
method: fetchType,
headers: headers,
body: body,
}).then(response => {
if (!response.ok) return response.text().then((text) => finalOnError(text));
else return response.json().then((json) => onResult(json));
}, (error) => {
console.log("Error in request at " + url);
});
}
export function textFetchWrapper(url: string, fetchType: FetchType, onResult?: (result: any) => void, body?: BodyInit, headers?: any) {
if (!headers) headers = {};
headers["Content-Type"] = "application/json";
let myFetch: any = fetch(url, {
method: fetchType,
headers: headers,
body: body,
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.text();
});
if (onResult) myFetch = myFetch.then((result: any) => onResult(result));
}