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