docbrown/app/javascript/utilities/http/request.js
Ridhwana 3f9b7c073c
Add a MultiSelect Autocomplete component to the Display Ads Page (#18560)
* feat: Add a pack file that pulls in the MultiSelect Component

* feat: move the tags to its own component

* save tags

* refactor: create a getCSRFToken function in the packs files so that it can be used in the admin

* feat: import the new module in request.js

* feat: remove unnecessary id

* feat: first pass of csrf token test

* chore: update the test

* fix: csrf token

* feat: hide the enw functionality behinda  feature flag

* fix: loading form twice

* refactor: import for csrftoken
2022-10-26 16:24:31 +02:00

55 lines
1.5 KiB
JavaScript

import { getCSRFToken } from './csrfToken';
/**
* Generic request with all the default headers required by the application.
*
* @example
* import { request } from '@utilities/http';
*
* const response = await request('/notification_subscriptions/Article/26')
*
* Note:
* The body option will typically be passed in as a JavaScript object.
* A check is performed for this and automatically convert it to JSON if necessary.
*
* Requests send JSON by default but this can be easily overridden by adding
* the Accept and Content-Type headers to the request options.
*
* The default method is GET.
*
* @param {string} url The URL to make the request to.
* @param {RequestInit} [options={}] The request options.
*
* @return {Promise<Response>} the response
*/
export async function request(url, options = {}) {
const {
headers,
body,
method = 'GET',
csrfToken = await getCSRFToken(),
// These are any other options that might be passed in e.g. keepalive
...restOfOptions
} = options;
// There should never be a scenario where null is passed as the body,
// but if ever there is, this logic should change.
const jsonifiedBody = {
body: body && typeof body !== 'string' ? JSON.stringify(body) : body,
};
const fetchOptions = {
method,
headers: {
Accept: 'application/json',
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json',
...headers,
},
credentials: 'same-origin',
...jsonifiedBody,
...restOfOptions,
};
return fetch(url, fetchOptions);
}