-
Notifications
You must be signed in to change notification settings - Fork 52
/
base.ts
37 lines (30 loc) · 1016 Bytes
/
base.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
import { SERVICE_API } from "@/app/base/sagas/http";
import { getCookie } from "@/app/utils";
export const API_ENDPOINTS = {
zones: "zones",
} as const;
export const DEFAULT_HEADERS = {
"Content-Type": "application/json",
Accept: "application/json",
};
export const handleErrors = (response: Response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
};
type ApiEndpoint = typeof API_ENDPOINTS;
export type ApiEndpointKey = keyof ApiEndpoint;
type ApiUrl = `${typeof SERVICE_API}${ApiEndpoint[ApiEndpointKey]}`;
export const getFullApiUrl = (endpoint: ApiEndpointKey): ApiUrl =>
`${SERVICE_API}${API_ENDPOINTS[endpoint]}`;
export const fetchWithAuth = async (url: string, options: RequestInit = {}) => {
const csrftoken = getCookie("csrftoken");
const headers = {
...DEFAULT_HEADERS,
"X-CSRFToken": csrftoken || "",
...options.headers,
};
const response = await fetch(url, { ...options, headers });
return handleErrors(response).json();
};