forked from gitroomhq/postiz-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom.fetch.func.ts
49 lines (46 loc) Β· 1.32 KB
/
custom.fetch.func.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
export interface Params {
baseUrl: string;
beforeRequest?: (url: string, options: RequestInit) => Promise<RequestInit>;
afterRequest?: (
url: string,
options: RequestInit,
response: Response
) => Promise<boolean>;
}
export const customFetch = (
params: Params,
auth?: string,
showorg?: string
) => {
return async function newFetch(url: string, options: RequestInit = {}) {
const newRequestObject = await params?.beforeRequest?.(url, options);
const fetchRequest = await fetch(params.baseUrl + url, {
credentials: 'include',
...(newRequestObject || options),
headers: {
...(auth ? { auth } : {}),
...(showorg ? { showorg } : {}),
...(options.body instanceof FormData
? {}
: { 'Content-Type': 'application/json' }),
Accept: 'application/json',
...options?.headers,
},
// @ts-ignore
...(!options.next && options.cache !== 'force-cache'
? { cache: options.cache || 'no-store' }
: {}),
});
if (
!params?.afterRequest ||
(await params?.afterRequest?.(url, options, fetchRequest))
) {
return fetchRequest;
}
// @ts-ignore
return new Promise((res) => {}) as Response;
};
};
export const fetchBackend = customFetch({
baseUrl: process.env.NEXT_PUBLIC_BACKEND_URL!,
});