You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
1.8 KiB
81 lines
1.8 KiB
import Axios, {AxiosError, AxiosRequestConfig, AxiosResponse} from "axios";
|
|
|
|
interface Response<T> {
|
|
code: number
|
|
message: string
|
|
data: T
|
|
}
|
|
|
|
export const authError = new Error("unauthenticated");
|
|
|
|
export async function getRequest<T>(url: string): Promise<T> {
|
|
const cors = url.includes("//");
|
|
|
|
return sendRequest<T>({
|
|
method: "GET",
|
|
url: cors ? url : `/api${url}`,
|
|
responseType: "json",
|
|
}, cors);
|
|
}
|
|
|
|
export function postRequest<T>(url: string, data: object = {}): Promise<T> {
|
|
return sendRequest<T>({
|
|
method: "POST",
|
|
url: `/api${url}`,
|
|
responseType: "json",
|
|
data,
|
|
});
|
|
}
|
|
|
|
export function putRequest<T>(url: string, data: object): Promise<T> {
|
|
return sendRequest<T>({
|
|
method: "PUT",
|
|
url: `/api${url}`,
|
|
responseType: "json",
|
|
data,
|
|
});
|
|
}
|
|
|
|
export function deleteRequest<T>(url: string): Promise<T> {
|
|
return sendRequest<T>({
|
|
method: "DELETE",
|
|
url: `/api${url}`,
|
|
responseType: "json",
|
|
});
|
|
}
|
|
|
|
async function sendRequest<T>(config: AxiosRequestConfig, cors: boolean = false): Promise<T> {
|
|
try {
|
|
const res = await Axios(config);
|
|
|
|
return await handleResponse(res, cors);
|
|
} catch (e) {
|
|
if (e === authError) {
|
|
throw e;
|
|
}
|
|
|
|
return await handleResponse((e as AxiosError).response as AxiosResponse);
|
|
}
|
|
}
|
|
|
|
function handleResponse<T>(response: AxiosResponse, object: boolean = false): Promise<T> {
|
|
if (object) {
|
|
return Promise.resolve(response.data);
|
|
} else {
|
|
const obj: Response<T> | undefined = response?.data;
|
|
|
|
if (![200, 201].includes(response.status)) {
|
|
if (response.status === 403) {
|
|
return Promise.reject(authError);
|
|
} else {
|
|
return Promise.reject(obj?.message || "Ukjent feil");
|
|
}
|
|
}
|
|
|
|
if (!obj) {
|
|
return Promise.reject("Ingen data mottatt");
|
|
}
|
|
|
|
return Promise.resolve(obj.data);
|
|
}
|
|
}
|