1import {isObject} from '../utils.js';
2
3const {csrfToken} = window.config;
4
5// safe HTTP methods that don't need a csrf token
6const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
7
8// fetch wrapper, use below method name functions and the `data` option to pass in data
9// which will automatically set an appropriate headers. For json content, only object
10// and array types are currently supported.
11export function request(url, {method = 'GET', data, headers = {}, ...other} = {}) {
12 let body, contentType;
13 if (data instanceof FormData || data instanceof URLSearchParams) {
14 body = data;
15 } else if (isObject(data) || Array.isArray(data)) {
16 contentType = 'application/json';
17 body = JSON.stringify(data);
18 }
19
20 const headersMerged = new Headers({
21 ...(!safeMethods.has(method) && {'x-csrf-token': csrfToken}),
22 ...(contentType && {'content-type': contentType}),
23 });
24
25 for (const [name, value] of Object.entries(headers)) {
26 headersMerged.set(name, value);
27 }
28
29 return fetch(url, {
30 method,
31 headers: headersMerged,
32 ...other,
33 ...(body && {body}),
34 });
35}
36
37export const GET = (url, opts) => request(url, {method: 'GET', ...opts});
38export const POST = (url, opts) => request(url, {method: 'POST', ...opts});
39export const PATCH = (url, opts) => request(url, {method: 'PATCH', ...opts});
40export const PUT = (url, opts) => request(url, {method: 'PUT', ...opts});
41export const DELETE = (url, opts) => request(url, {method: 'DELETE', ...opts});