Skip to content

Commit

Permalink
Refactor request function
Browse files Browse the repository at this point in the history
- Remove and preven use of `body` argument, it is not used anywhere
- Remove uppercasing of method, we can require it to be uppercase
  • Loading branch information
silverwind committed Feb 15, 2024
1 parent 21331be commit c9ec863
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions web_src/js/modules/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,17 @@ const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
// fetch wrapper, use below method name functions and the `data` option to pass in data
// 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} = {}) {
let contentType;
if (!body) {
if (data instanceof FormData || data instanceof URLSearchParams) {
body = data;
} else if (isObject(data) || Array.isArray(data)) {
contentType = 'application/json';
body = JSON.stringify(data);
}
export function request(url, {method = 'GET', headers = {}, data, ...other} = {}) {
let body, contentType;
if (data instanceof FormData || data instanceof URLSearchParams) {
body = data;
} else if (isObject(data) || Array.isArray(data)) {
contentType = 'application/json';
body = JSON.stringify(data);
}

const headersMerged = new Headers({
...(!safeMethods.has(method.toUpperCase()) && {'x-csrf-token': csrfToken}),
...(!safeMethods.has(method) && {'x-csrf-token': csrfToken}),
...(contentType && {'content-type': contentType}),
});

Expand All @@ -31,8 +29,8 @@ export function request(url, {method = 'GET', headers = {}, data, body, ...other
return fetch(url, {
method,
headers: headersMerged,
...(body && {body}),
...other,
...(body && {body}),
});
}

Expand Down

0 comments on commit c9ec863

Please sign in to comment.