-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
55 lines (49 loc) · 1.21 KB
/
client.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
import { Api } from "./api";
import Cookies from "js-cookie";
import { useSelector } from "react-redux";
interface GetApiParamTypes {
cookie: string;
xcsrfToken: string;
}
export function getApi(props: GetApiParamTypes): typeof Api.prototype.api {
const isServer = typeof window === "undefined";
let headers: any = {
"X-CSRFToken": props.xcsrfToken,
}
if (props.cookie) {
headers = {
...headers,
cookie: props.cookie,
}
}
const api = new Api({
baseUrl: isServer ? "http://backend:8000" : "",
baseApiParams: {
headers
},
});
return api.api;
}
export function getApiClient(pageContext: any) {
return getApi({
cookie: pageContext.cookie,
xcsrfToken: pageContext.xcsrfToken,
});
}
export function getApiServer(pageContext: any) {
return getApi({
cookie: pageContext.requestHeaders.cookie,
xcsrfToken: pageContext.xcsrfToken,
});
}
export function useApi() {
const frontend = useSelector((state: any) => state.frontend);
const isServer = typeof window === "undefined";
return isServer ? getApi({
cookie: frontend.cookie,
xcsrfToken: frontend.xcsrfToken,
}) : getApi({
xcsrfToken: Cookies.get("csrftoken") || "",
cookie: null
})
}