fradrive/frontend/src/services/http-client/http-client.js
2022-10-12 09:35:16 +02:00

88 lines
2.5 KiB
JavaScript

// SPDX-FileCopyrightText: 2022 Gregor Kleen <gregor.kleen@ifi.lmu.de>,Sarah Vaupel <sarah.vaupel@ifi.lmu.de>,Sarah Vaupel <vaupel.sarah@campus.lmu.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
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);
}
}
removeResponseInterceptor(interceptor) {
//performs a reference check. if the interceptor is bound, when adding it, the reference of the bound function needs to be the same when removing it later.
if (typeof interceptor !== 'function') {
throw new Error(`Cannot remove Interceptor ${interceptor}, because it is not of type function`);
}
if(this._responseInterceptors.filter(el => el == interceptor).length === 0) {
throw new Error(`Could not find Response Interceptor ${interceptor}.`);
}
this._responseInterceptors = this._responseInterceptors.filter(el => el !== interceptor);
}
_baseUrl;
setBaseUrl(baseUrl) {
if (typeof this._baseUrl !== 'undefined') {
throw new Error('HttpClient baseUrl is already set');
}
this._baseUrl = baseUrl;
}
_defaultUrl;
setDefaultUrl(defaultUrl) {
if (typeof this._defaultUrl !== 'undefined') {
throw new Error('HttpClient defaultUrl is already set');
}
this._defaultUrl = defaultUrl;
}
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) {
options.url = (options.url && options.url.href) || options.url || this._defaultUrl;
if (this._baseUrl && options.url && options.url.substring(0,1) === '/' && options.url.substring(0,2) !== '//')
options.url = this._baseUrl + (this._baseUrl.substring(this._baseUrl.substring.length - 1) === '/' ? '' : '/') + options.url.substring(1,0);
const requestOptions = {
credentials: 'same-origin',
...options,
};
return fetch(options.url || window.location.href, requestOptions)
.then(
(response) => {
this._responseInterceptors.forEach((interceptor) => interceptor(response, options));
return Promise.resolve(response);
},
Promise.reject,
).catch(console.error);
}
}