* Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
(config, reqData, reqHeaders)
| 9106 | * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests |
| 9107 | */ |
| 9108 | function sendReq(config, reqData, reqHeaders) { |
| 9109 | var deferred = $q.defer(), |
| 9110 | promise = deferred.promise, |
| 9111 | cache, |
| 9112 | cachedResp, |
| 9113 | url = buildUrl(config.url, config.params); |
| 9114 | |
| 9115 | $http.pendingRequests.push(config); |
| 9116 | promise.then(removePendingReq, removePendingReq); |
| 9117 | |
| 9118 | |
| 9119 | if (config.cache && config.method == 'GET') { |
| 9120 | cache = isObject(config.cache) ? config.cache : defaultCache; |
| 9121 | } |
| 9122 | |
| 9123 | if (cache) { |
| 9124 | cachedResp = cache.get(url); |
| 9125 | if (cachedResp) { |
| 9126 | if (cachedResp.then) { |
| 9127 | // cached request has already been sent, but there is no response yet |
| 9128 | cachedResp.then(removePendingReq, removePendingReq); |
| 9129 | return cachedResp; |
| 9130 | } else { |
| 9131 | // serving from cache |
| 9132 | if (isArray(cachedResp)) { |
| 9133 | resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); |
| 9134 | } else { |
| 9135 | resolvePromise(cachedResp, 200, {}); |
| 9136 | } |
| 9137 | } |
| 9138 | } else { |
| 9139 | // put the promise for the non-transformed response into cache as a placeholder |
| 9140 | cache.put(url, promise); |
| 9141 | } |
| 9142 | } |
| 9143 | |
| 9144 | // if we won't have the response in cache, send the request to the backend |
| 9145 | if (!cachedResp) { |
| 9146 | $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, |
| 9147 | config.withCredentials); |
| 9148 | } |
| 9149 | |
| 9150 | return promise; |
| 9151 | |
| 9152 | |
| 9153 | /** |
| 9154 | * Callback registered to $httpBackend(): |
| 9155 | * - caches the response if desired |
| 9156 | * - resolves the raw $http promise |
| 9157 | * - calls $apply |
| 9158 | */ |
| 9159 | function done(status, response, headersString) { |
| 9160 | if (cache) { |
| 9161 | if (isSuccess(status)) { |
| 9162 | cache.put(url, [status, response, parseHeaders(headersString)]); |
| 9163 | } else { |
| 9164 | // remove promise from the cache |
| 9165 | cache.remove(url); |