2024-05-23 10:50:13 +01:00
|
|
|
import type { AxiosResponse, Method, RawAxiosRequestHeaders } from 'axios';
|
2023-09-11 15:09:22 +01:00
|
|
|
import axios from 'axios';
|
|
|
|
import LinkHeader from 'http-link-header';
|
|
|
|
|
2024-05-22 15:45:18 +01:00
|
|
|
import { getAccessToken } from './initial_state';
|
2023-09-11 15:09:22 +01:00
|
|
|
import ready from './ready';
|
|
|
|
|
|
|
|
export const getLinks = (response: AxiosResponse) => {
|
|
|
|
const value = response.headers.link as string | undefined;
|
|
|
|
|
|
|
|
if (!value) {
|
|
|
|
return new LinkHeader();
|
|
|
|
}
|
|
|
|
|
|
|
|
return LinkHeader.parse(value);
|
|
|
|
};
|
|
|
|
|
|
|
|
const csrfHeader: RawAxiosRequestHeaders = {};
|
|
|
|
|
|
|
|
const setCSRFHeader = () => {
|
|
|
|
const csrfToken = document.querySelector<HTMLMetaElement>(
|
|
|
|
'meta[name=csrf-token]',
|
|
|
|
);
|
|
|
|
|
|
|
|
if (csrfToken) {
|
|
|
|
csrfHeader['X-CSRF-Token'] = csrfToken.content;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
void ready(setCSRFHeader);
|
|
|
|
|
2024-05-22 15:45:18 +01:00
|
|
|
const authorizationTokenFromInitialState = (): RawAxiosRequestHeaders => {
|
|
|
|
const accessToken = getAccessToken();
|
2024-03-27 12:47:09 +00:00
|
|
|
|
2024-05-22 15:45:18 +01:00
|
|
|
if (!accessToken) return {};
|
2023-09-11 15:09:22 +01:00
|
|
|
|
|
|
|
return {
|
|
|
|
Authorization: `Bearer ${accessToken}`,
|
2024-05-22 15:45:18 +01:00
|
|
|
};
|
2023-09-11 15:09:22 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// eslint-disable-next-line import/no-default-export
|
2024-05-23 08:30:48 +01:00
|
|
|
export default function api(withAuthorization = true) {
|
2023-09-11 15:09:22 +01:00
|
|
|
return axios.create({
|
|
|
|
headers: {
|
|
|
|
...csrfHeader,
|
2024-05-23 08:30:48 +01:00
|
|
|
...(withAuthorization ? authorizationTokenFromInitialState() : {}),
|
2023-09-11 15:09:22 +01:00
|
|
|
},
|
|
|
|
|
|
|
|
transformResponse: [
|
|
|
|
function (data: unknown) {
|
|
|
|
try {
|
|
|
|
return JSON.parse(data as string) as unknown;
|
|
|
|
} catch {
|
|
|
|
return data;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
],
|
|
|
|
});
|
|
|
|
}
|
2024-05-23 10:50:13 +01:00
|
|
|
|
|
|
|
export async function apiRequest<ApiResponse = unknown>(
|
|
|
|
method: Method,
|
|
|
|
url: string,
|
2024-05-23 19:22:42 +01:00
|
|
|
params?: Record<string, unknown>,
|
2024-05-23 10:50:13 +01:00
|
|
|
) {
|
|
|
|
const { data } = await api().request<ApiResponse>({
|
|
|
|
method,
|
2024-05-23 19:22:42 +01:00
|
|
|
url: '/api/' + url,
|
|
|
|
data: params,
|
2024-05-23 10:50:13 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|