All files / ima/http HttpAgentImpl.js

89.61% Statements 69/77
51.85% Branches 14/27
90.48% Functions 19/21
89.61% Lines 69/77
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443        3x                                                                                 20x             20x             20x               20x             20x                             20x                                   20x             4x             4x                       4x                       4x                       4x                       64x                                                                     20x   20x 4x   4x         20x                                       4x   4x       4x           4x                                   25x   25x     15x 10x     25x   25x                         15x             15x           15x   15x 5x     15x 15x 15x     15x 15x     15x                                         10x 10x 10x 10x   10x 5x   5x   5x 5x   5x 5x 5x 5x                           20x         20x             20x           20x                             64x                   5x 5x   5x 5x 10x                         15x           15x 15x 15x 15x       3x  
import ns from '../namespace';
import HttpAgent from './HttpAgent';
import GenericError from '../error/GenericError';
 
ns.namespace('ima.http');
 
/**
 * Implementation of the {@codelink HttpAgent} interface with internal caching
 * of completed and ongoing HTTP requests and cookie storage.
 */
export default class HttpAgentImpl extends HttpAgent {
  /**
	 * Initializes the HTTP handler.
	 *
	 * @param {HttpProxy} proxy The low-level HTTP proxy for sending the HTTP
	 *        requests.
	 * @param {Cache} cache Cache to use for caching ongoing and completed
	 *        requests.
	 * @param {CookieStorage} cookie The cookie storage to use internally.
	 * @param {Object<string, *>} config Configuration of the HTTP handler for
	 *        the current application environment, specifying the various
	 *        default request option values and cache option values.
	 * @example
	 *      http
	 *          .get('url', { data: data }, {
	 *              ttl: 2000,
	 *              repeatRequest: 1,
	 *              withCredentials: true,
	 *              timeout: 2000,
	 *              accept: 'application/json',
	 *              language: 'en',
	 *              listeners: { 'progress': callbackFunction }
	 *          })
	 *          .then((response) => {
	 *              //resolve
	 *          }
	 *          .catch((error) => {
	 *             //catch
	 *          });
	 * @example
	 *      http
	 *          .setDefaultHeader('Accept-Language', 'en')
	 *          .clearDefaultHeaders();
	 */
  constructor(proxy, cache, cookie, config) {
    super();
 
    /**
		 * HTTP proxy, used to execute the HTTP requests.
		 *
		 * @type {HttpProxy}
		 */
    this._proxy = proxy;
 
    /**
		 * Internal request cache, used to cache completed request results.
		 *
		 * @type {Cache}
		 */
    this._cache = cache;
 
    /**
		 * Cookie storage, used to keep track of cookies received from the
		 * server and send them with the subsequent requests to the server.
		 *
		 * @type {CookieStorage}
		 */
    this._cookie = cookie;
 
    /**
		 * Cache options.
		 *
		 * @type {Object<string, string>}
		 */
    this._cacheOptions = config.cacheOptions;
 
    /**
		 * Default request options.
		 *
		 * @type {{
		 *         timeout: number,
		 *         ttl: number,
		 *         repeatRequest: number,
		 *         headers: Object<string, string>,
		 *         cache: boolean,
		 *         withCredentials: boolean,
		 *         postProcessor: function(Object<string, *>)
		 *       }}
		 */
    this._defaultRequestOptions = config.defaultRequestOptions;
 
    /**
		 * Internal request cache, used to cache ongoing requests.
		 *
		 * @type {Map<string, Promise<{
		 *         status: number,
		 *         body: *,
		 *         params: {
		 *           method: string,
		 *           url: string,
		 *           transformedUrl: string,
		 *           data: Object<string, (boolean|number|string)>
		 *         },
		 *         headers: Object<string, string>,
		 *         cached: boolean
		 *       }>>}
		 */
    this._internalCacheOfPromises = new Map();
  }
 
  /**
	 * @inheritdoc
	 */
  get(url, data, options = {}) {
    return this._requestWithCheckCache('get', url, data, options);
  }
 
  /**
	 * @inheritdoc
	 */
  post(url, data, options = {}) {
    return this._requestWithCheckCache(
      'post',
      url,
      data,
      Object.assign({}, options, { cache: false })
    );
  }
 
  /**
	 * @inheritdoc
	 */
  put(url, data, options = {}) {
    return this._requestWithCheckCache(
      'put',
      url,
      data,
      Object.assign({}, options, { cache: false })
    );
  }
 
  /**
	 * @inheritdoc
	 */
  patch(url, data, options = {}) {
    return this._requestWithCheckCache(
      'patch',
      url,
      data,
      Object.assign({}, options, { cache: false })
    );
  }
 
  /**
	 * @inheritdoc
	 */
  delete(url, data, options = {}) {
    return this._requestWithCheckCache(
      'delete',
      url,
      data,
      Object.assign({}, options, { cache: false })
    );
  }
 
  /**
	 * @inheritdoc
	 */
  getCacheKey(method, url, data) {
    return (
      this._cacheOptions.prefix + this._getCacheKeySuffix(method, url, data)
    );
  }
 
  /**
	 * @inheritdoc
	 */
  setDefaultHeader(header, value) {
    this._proxy.setDefaultHeader(header, value);
 
    return this;
  }
 
  /**
	 * @inheritdoc
	 */
  clearDefaultHeaders() {
    this._proxy.clearDefaultHeaders();
 
    return this;
  }
 
  /**
	 * Check cache and if data isnt available then make real request.
	 *
	 * @param {string} method The HTTP method to use.
	 * @param {string} url The URL to which the request should be sent.
	 * @param {Object<string, (boolean|number|string|Date)>} data The data to
	 *        send with the request.
	 * @param {HttpAgent~RequestOptions=} options Optional request options.
	 * @return {Promise<HttpAgent~Response>} A promise that resolves to the response
	 *         with body parsed as JSON.
	 */
  _requestWithCheckCache(method, url, data, options) {
    options = this._prepareOptions(options);
 
    if (options.cache) {
      let cachedData = this._getCachedData(method, url, data);
 
      Iif (cachedData) {
        return cachedData;
      }
    }
 
    return this._request(method, url, data, options);
  }
 
  /**
	 * Tests whether an ongoing or completed HTTP request for the specified URL
	 * and data is present in the internal cache and, if it is, the method
	 * returns a promise that resolves to the response body parsed as JSON.
	 *
	 * The method returns {@code null} if no such request is present in the
	 * cache.
	 *
	 * @param {string} method The HTTP method used by the request.
	 * @param {string} url The URL to which the request was made.
	 * @param {Object<string, (boolean|number|string|Date)>} data The data sent
	 *        to the server with the request.
	 * @return {?Promise<HttpAgent~Response>} A promise that will resolve to the
	 *         server response with the body parsed as JSON, or {@code null} if
	 *         no such request is present in the cache.
	 */
  _getCachedData(method, url, data) {
    let cacheKey = this.getCacheKey(method, url, data);
 
    Iif (this._internalCacheOfPromises.has(cacheKey)) {
      return this._internalCacheOfPromises.get(cacheKey);
    }
 
    Iif (this._cache.has(cacheKey)) {
      let cacheData = this._cache.get(cacheKey);
 
      return Promise.resolve(cacheData);
    }
 
    return null;
  }
 
  /**
	 * Sends a new HTTP request using the specified method to the specified
	 * url. The request will carry the provided data as query parameters if the
	 * HTTP method is GET, but the data will be sent as request body for any
	 * other request method.
	 *
	 * @param {string} method HTTP method to use.
	 * @param {string} url The URL to which the request is sent.
	 * @param {Object<string, (boolean|number|string|Date)>} data The data sent
	 *        with the request.
	 * @param {HttpAgent~RequestOptions=} options Optional request options.
	 * @return {Promise<HttpAgent~Response>} A promise that resolves to the response
	 *         with the body parsed as JSON.
	 */
  _request(method, url, data, options) {
    let cacheKey = this.getCacheKey(method, url, data);
 
    let cachePromise = this._proxy
      .request(method, url, data, options)
      .then(
        response => this._proxyResolved(response),
        error => this._proxyRejected(error)
      );
 
    this._internalCacheOfPromises.set(cacheKey, cachePromise);
 
    return cachePromise;
  }
 
  /**
	 * Handles successful completion of an HTTP request by the HTTP proxy.
	 *
	 * The method also updates the internal cookie storage with the cookies
	 * received from the server.
	 *
	 * @param {HttpAgent~Response} response Server response.
	 * @return {HttpAgent~Response} The post-processed server response.
	 */
  _proxyResolved(response) {
    let agentResponse = {
      status: response.status,
      body: response.body,
      params: response.params,
      headers: response.header,
      cached: false
    };
    let cacheKey = this.getCacheKey(
      agentResponse.params.method,
      agentResponse.params.url,
      agentResponse.params.data
    );
 
    this._internalCacheOfPromises.delete(cacheKey);
 
    if (this._proxy.haveToSetCookiesManually()) {
      this._setCookiesFromResponse(agentResponse);
    }
 
    let { postProcessor, cache } = agentResponse.params.options;
    Eif (typeof postProcessor === 'function') {
      agentResponse = postProcessor(agentResponse);
    }
 
    Eif (cache) {
      this._saveAgentResponseToCache(agentResponse);
    }
 
    return agentResponse;
  }
 
  /**
	 * Handles rejection of the HTTP request by the HTTP proxy. The method
	 * tests whether there are any remaining tries for the request, and if
	 * there are any, it attempts re-send the request.
	 *
	 * The method rejects the internal request promise if there are no tries
	 * left.
	 *
	 * @param {GenericError} error The error provided by the HttpProxy,
	 *        carrying the error parameters, such as the request url, data,
	 *        method, options and other useful data.
	 * @return {Promise<HttpAgent~Response>} A promise that will either resolve to a
	 *         server's response (with the body parsed as JSON) if there are
	 *         any tries left and the re-tried request succeeds, or rejects
	 *         with an error containing details of the cause of the request's
	 *         failure.
	 */
  _proxyRejected(error) {
    let errorParams = error.getParams();
    let method = errorParams.method;
    let url = errorParams.url;
    let data = errorParams.data;
 
    if (errorParams.options.repeatRequest > 0) {
      errorParams.options.repeatRequest--;
 
      return this._request(method, url, data, errorParams.options);
    } else {
      let cacheKey = this.getCacheKey(method, url, data);
      this._internalCacheOfPromises.delete(cacheKey);
 
      let errorName = errorParams.errorName;
      let errorMessage = `${errorName}: ima.http.Agent:_proxyRejected: ${error.message}`;
      let agentError = new GenericError(errorMessage, errorParams);
      return Promise.reject(agentError);
    }
  }
 
  /**
	 * Prepares the provided request options object by filling in missing
	 * options with default values and addding extra options used internally.
	 *
	 * @param {HttpAgent~RequestOptions} options Optional request options.
	 * @return {HttpAgent~RequestOptions} Request options with set filled-in
	 *         default values for missing fields, and extra options used
	 *         internally.
	 */
  _prepareOptions(options) {
    let extraOptions = {
      cookie: this._cookie.getCookiesStringForCookieHeader(),
      headers: {}
    };
 
    let composedOptions = Object.assign(
      {},
      this._defaultRequestOptions,
      extraOptions,
      options
    );
 
    composedOptions.headers = Object.assign(
      {},
      this._defaultRequestOptions.headers,
      options.headers || {}
    );
 
    return composedOptions;
  }
 
  /**
	 * Generates cache key suffix for an HTTP request to the specified URL with
	 * the specified data.
	 *
	 * @param {string} method The HTTP method used by the request.
	 * @param {string} url The URL to which the request is sent.
	 * @param {Object<string, (boolean|number|string|Date)>} data The data sent
	 *        with the request.
	 * @return {string} The suffix of a cache key to use for a request to the
	 *         specified URL, carrying the specified data.
	 */
  _getCacheKeySuffix(method, url, data) {
    return `${method}:${url}?${JSON.stringify(data)}`;
  }
 
  /**
	 * Sets all cookies from the {@code Set-Cookie} response header to the
	 * cookie storage.
	 *
	 * @param {HttpAgent~Response} agentResponse The response of the server.
	 */
  _setCookiesFromResponse(agentResponse) {
    Eif (agentResponse.headers) {
      let receivedCookies = agentResponse.headers['set-cookie'];
 
      Eif (receivedCookies) {
        receivedCookies.forEach(cookieHeader => {
          this._cookie.parseFromSetCookieHeader(cookieHeader);
        });
      }
    }
  }
 
  /**
	 * Saves the server response to the cache to be used as the result of the
	 * next request of the same properties.
	 *
	 * @param {HttpAgent~Response} agentResponse The response of the server.
	 */
  _saveAgentResponseToCache(agentResponse) {
    let cacheKey = this.getCacheKey(
      agentResponse.params.method,
      agentResponse.params.url,
      agentResponse.params.data
    );
 
    agentResponse.cached = true;
    let ttl = agentResponse.params.options.ttl;
    this._cache.set(cacheKey, agentResponse, ttl);
    agentResponse.cached = false;
  }
}
 
ns.ima.http.HttpAgentImpl = HttpAgentImpl;