From 373c8d213d397cd8b3f38a73abe5b76348ee329c Mon Sep 17 00:00:00 2001 From: Felix Hamann Date: Thu, 9 May 2019 21:54:50 +0200 Subject: [PATCH] add interceptors to http client --- static/js/services/httpClient.js | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/static/js/services/httpClient.js b/static/js/services/httpClient.js index 32935cb07..eacd9b6b5 100644 --- a/static/js/services/httpClient.js +++ b/static/js/services/httpClient.js @@ -1,8 +1,16 @@ -(function collonadeClosure() { +(function () { 'use strict'; window.HttpClient = (function() { + var _responseInterceptors = []; + + function addResponseInterceptor(interceptor) { + if (typeof interceptor === 'function') { + _responseInterceptors.push(interceptor); + } + } + function _fetch(url, method, additionalHeaders, body) { var requestOptions = { credentials: 'same-origin', @@ -15,7 +23,17 @@ requestOptions.headers[headerKey] = additionalHeaders[headerKey]; }); - return fetch(url, requestOptions); + return fetch(url, requestOptions).then( + function(response) { + _responseInterceptors.forEach(function(interceptor) { interceptor(response); }); + return Promise.resolve(response); + }, + function(error) { + return Promise.reject(error); + } + ).catch(function(error) { + console.error(error); + }); } return { @@ -25,6 +43,7 @@ post: function(url, headers, body) { return _fetch(url, 'POST', headers, body); }, + addResponseInterceptor: addResponseInterceptor, } })(); })();