-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetchApi.ts
58 lines (52 loc) · 1.34 KB
/
fetchApi.ts
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
type FetchApiProps = {
method: "get" | "post" | "delete" | "put" | "patch";
url: string;
body?: any; //optional when using get, can be any JSON object so set as any
headers?: any; // if empty set default with JSOn content-type and no token
};
const fetchApi = (props: FetchApiProps) => {
console.log("fetchApi", props);
let { method, body, url, headers } = props;
console.log("method", method);
console.log("body", body);
console.log("url", url);
console.log("headers", headers);
if (
!method ||
(method === "post" && !body) ||
(method === "put" && !body) ||
!url
)
return Promise.reject("one of the props is null");
console.log("fetchApi2");
if (!headers) {
console.log("no header");
headers = {
Accept: "application/json",
"Content-Type": "application/json",
};
}
return fetch(
url,
method === "get"
? {
method,
headers,
}
: {
method,
headers,
body,
}
)
.then((response) => {
console.log("response status", response.status);
if (response.status >= 200 && response.status <= 299) {
return response.json();
} else {
throw Error("Error with status " + response);
}
})
.catch((err) => console.log("err", JSON.stringify(err)));
};
export default fetchApi;