-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapiActions.ts
More file actions
77 lines (68 loc) · 1.98 KB
/
apiActions.ts
File metadata and controls
77 lines (68 loc) · 1.98 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
75
76
77
import { AxiosRequestConfig } from 'axios';
import { customInstance } from '../../../mock/mutator/customClient';
type SecondParameter<T extends (...args: any) => any> = Parameters<T>[1];
interface CustomRequestConfig extends AxiosRequestConfig {
handleRedirect?: boolean;
}
export const createPostRequest = <T = any, D = any>(endpoint: string, headers: object) => {
return async (data?: D, options?: CustomRequestConfig) => {
// Use fetch for handling redirect responses
if (options?.handleRedirect) {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
...headers,
},
body: JSON.stringify(data),
credentials: 'include',
redirect: 'manual'
});
// Default response handling
const text = await response.text();
try {
const json = JSON.parse(text);
return {
raw: json,
status: response.status
};
} catch {
return {
raw: text,
status: response.status
};
}
}
// Default axios behavior for normal requests
return customInstance<T>(
{
url: endpoint,
method: "POST",
data: data,
headers: headers,
withCredentials: true
},
options,
)
}
}
export const createGetRequest = <T = any, P = any>(endpoint: string, contentType?: string) => {
return (params?: P, options?: SecondParameter<typeof customInstance>, signal?: AbortSignal) => {
const absUrl = endpoint.startsWith('http')
? endpoint
: new URL(endpoint.startsWith('/') ? endpoint : `/${endpoint}`, window.location.origin).toString();
const config: AxiosRequestConfig = {
url: absUrl,
method: "GET",
params,
signal,
withCredentials: true
};
if (contentType) {
config.headers = {
...config.headers,
Accept: contentType,
};
}
return customInstance<T>(config, options).then(response => response);
}
}