-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiWrapper.ts
45 lines (43 loc) · 977 Bytes
/
apiWrapper.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
import axios from "axios";
export const apiWrapper = async (
method: "GET" | "POST",
url: string,
generalErrorMessage: string,
params?: any,
timeout?: number,
) => {
let response;
let handler;
switch (method) {
case "GET":
handler = axios.get;
break;
case "POST":
handler = axios.post;
break;
default:
throw new Error("Invalid method");
}
try {
// destructure params in case of post request
response = await handler(
`${process.env.NEXT_PUBLIC_FINALITY_GADGET_API_URL}${url}`,
method === "POST"
? { ...params }
: {
params,
},
{
timeout: timeout || 0, // 0 is no timeout
},
);
} catch (error) {
if (axios.isAxiosError(error)) {
const message = error?.response?.data?.message;
throw new Error(message || generalErrorMessage);
} else {
throw new Error(generalErrorMessage);
}
}
return response;
};