This repository has been archived on 2024-10-24. You can view files and clone it, but cannot push or open issues or pull requests.
fradrive-old/frontend/src/services/http-client/http-client.js

46 lines
977 B
JavaScript

import Cookies from 'js-cookie';
export class HttpClient {
static ACCEPT = {
TEXT_HTML: 'text/html',
JSON: 'application/json',
};
_responseInterceptors = [];
addResponseInterceptor(interceptor) {
if (typeof interceptor === 'function') {
this._responseInterceptors.push(interceptor);
}
}
get(args) {
args.method = 'GET';
return this._fetch(args);
}
post(args) {
args.method = 'POST';
args.headers = args.headers || {};
args.headers['X-XSRF-TOKEN'] = Cookies.get('XSRF-TOKEN');
return this._fetch(args);
}
_fetch(options) {
const requestOptions = {
credentials: 'same-origin',
...options,
};
return fetch(options.url, requestOptions)
.then(
(response) => {
this._responseInterceptors.forEach((interceptor) => interceptor(response, options));
return Promise.resolve(response);
},
Promise.reject,
).catch(console.error);
}
}