2023-09-11 10:25:10 +02:00
|
|
|
import {isObject} from '../utils.js';
|
|
|
|
|
|
|
|
const {csrfToken} = window.config;
|
|
|
|
|
2023-09-19 02:50:30 +02:00
|
|
|
// safe HTTP methods that don't need a csrf token
|
|
|
|
const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
|
|
|
|
|
2023-09-11 10:25:10 +02:00
|
|
|
// fetch wrapper, use below method name functions and the `data` option to pass in data
|
2023-09-19 02:50:30 +02:00
|
|
|
// which will automatically set an appropriate headers. For json content, only object
|
|
|
|
// and array types are currently supported.
|
|
|
|
export function request(url, {method = 'GET', headers = {}, data, body, ...other} = {}) {
|
2023-09-11 10:25:10 +02:00
|
|
|
let contentType;
|
|
|
|
if (!body) {
|
2023-10-11 14:34:21 +02:00
|
|
|
if (data instanceof FormData || data instanceof URLSearchParams) {
|
2023-09-11 10:25:10 +02:00
|
|
|
body = data;
|
|
|
|
} else if (isObject(data) || Array.isArray(data)) {
|
|
|
|
contentType = 'application/json';
|
|
|
|
body = JSON.stringify(data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-19 02:50:30 +02:00
|
|
|
const headersMerged = new Headers({
|
|
|
|
...(!safeMethods.has(method.toUpperCase()) && {'x-csrf-token': csrfToken}),
|
|
|
|
...(contentType && {'content-type': contentType}),
|
|
|
|
});
|
|
|
|
|
|
|
|
for (const [name, value] of Object.entries(headers)) {
|
|
|
|
headersMerged.set(name, value);
|
|
|
|
}
|
|
|
|
|
2023-09-11 10:25:10 +02:00
|
|
|
return fetch(url, {
|
2023-09-19 02:50:30 +02:00
|
|
|
method,
|
|
|
|
headers: headersMerged,
|
2023-09-11 10:25:10 +02:00
|
|
|
...(body && {body}),
|
|
|
|
...other,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export const GET = (url, opts) => request(url, {method: 'GET', ...opts});
|
|
|
|
export const POST = (url, opts) => request(url, {method: 'POST', ...opts});
|
|
|
|
export const PATCH = (url, opts) => request(url, {method: 'PATCH', ...opts});
|
|
|
|
export const PUT = (url, opts) => request(url, {method: 'PUT', ...opts});
|
|
|
|
export const DELETE = (url, opts) => request(url, {method: 'DELETE', ...opts});
|