philomena/assets/js/utils/requests.ts

40 lines
946 B
TypeScript
Raw Normal View History

// Request Utils
2019-10-05 02:09:52 +02:00
2022-03-26 00:17:37 +01:00
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH';
export function fetchJson(verb: HttpMethod, endpoint: string, body?: Record<string, unknown>): Promise<Response> {
const data: RequestInit = {
2019-10-05 02:09:52 +02:00
method: verb,
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
2020-09-28 05:53:14 +02:00
'x-csrf-token': window.booru.csrfToken,
2024-07-03 22:54:14 +02:00
'x-requested-with': 'xmlhttprequest',
2019-10-05 02:09:52 +02:00
},
};
if (body) {
body._method = verb;
data.body = JSON.stringify(body);
}
return fetch(endpoint, data);
}
2022-03-26 00:17:37 +01:00
export function fetchHtml(endpoint: string): Promise<Response> {
2019-10-05 02:09:52 +02:00
return fetch(endpoint, {
credentials: 'same-origin',
headers: {
2020-09-28 05:53:14 +02:00
'x-csrf-token': window.booru.csrfToken,
2024-07-03 22:54:14 +02:00
'x-requested-with': 'xmlhttprequest',
2019-10-05 02:09:52 +02:00
},
});
}
2022-03-26 00:17:37 +01:00
export function handleError(response: Response): Response {
2019-10-05 02:09:52 +02:00
if (!response.ok) {
throw new Error('Received error from server');
}
return response;
}