misc_pterodactyl-panel/resources/scripts/api/http.ts

113 lines
2.8 KiB
TypeScript
Raw Normal View History

import axios, { AxiosInstance } from 'axios';
import { store } from '@/state';
const http: AxiosInstance = axios.create({
timeout: 20000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
2020-07-05 01:30:50 +00:00
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
http.interceptors.request.use(req => {
const cookies = document.cookie.split(';').reduce((obj, val) => {
const [ key, value ] = val.trim().split('=').map(decodeURIComponent);
return { ...obj, [key]: value };
}, {} as Record<string, string>);
req.headers['X-XSRF-TOKEN'] = cookies['XSRF-TOKEN'] || 'nil';
return req;
});
http.interceptors.request.use(req => {
2022-05-04 23:19:00 +00:00
if (!req.url?.endsWith('/resources')) {
store.getActions().progress.startContinuous();
}
return req;
});
http.interceptors.response.use(resp => {
2022-05-04 23:19:00 +00:00
if (!resp.request?.url?.endsWith('/resources')) {
store.getActions().progress.setComplete();
}
return resp;
}, error => {
2020-04-17 17:26:36 +00:00
store.getActions().progress.setComplete();
throw error;
});
export default http;
/**
* Converts an error into a human readable response. Mostly just a generic helper to
* make sure we display the message from the server back to the user if we can.
*/
export function httpErrorToHuman (error: any): string {
if (error.response && error.response.data) {
let { data } = error.response;
// Some non-JSON requests can still return the error as a JSON block. In those cases, attempt
// to parse it into JSON so we can display an actual error.
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) {
// do nothing, bad json
}
}
if (data.errors && data.errors[0] && data.errors[0].detail) {
return data.errors[0].detail;
}
2020-08-23 05:35:53 +00:00
// Errors from wings directory, mostly just for file uploads.
if (data.error && typeof data.error === 'string') {
return data.error;
}
}
return error.message;
}
2019-11-03 20:20:11 +00:00
export interface FractalResponseData {
object: string;
attributes: {
[k: string]: any;
relationships?: Record<string, FractalResponseData | FractalResponseList>;
2019-11-03 20:20:11 +00:00
};
}
export interface FractalResponseList {
object: 'list';
data: FractalResponseData[];
}
export interface PaginatedResult<T> {
items: T[];
pagination: PaginationDataSet;
}
interface PaginationDataSet {
total: number;
count: number;
perPage: number;
currentPage: number;
totalPages: number;
}
export function getPaginationSet (data: any): PaginationDataSet {
return {
total: data.total,
count: data.count,
perPage: data.per_page,
currentPage: data.current_page,
totalPages: data.total_pages,
};
}