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'; 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); } } window.HttpClient = new HttpClient(); // HttpClient ships with its own little interceptor to throw an error // if the response does not match the expected content-type function contentTypeInterceptor(response, options) { if (!options || !options.accept) { return; } const contentType = response.headers.get("content-type"); if (!contentType.match(options.accept)) { throw new Error('Server returned with "' + contentType + '" when "' + options.accept + '" was expected'); } } window.HttpClient.addResponseInterceptor(contentTypeInterceptor);