All files / lib/agent/batch Response.js

100% Statements 78/78
95.65% Branches 22/23
95.23% Functions 20/21
100% Lines 78/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    27x 27x 27x 27x 27x 27x                                         26x   26x   26x 26x         26x         26x         26x                           4x 4x     4x     4x     4x 4x 4x 4x 4x     10x           3x 3x 1x 1x     1x 1x 1x     4x                           1x     5x 2x   3x   5x         1x                                                   5x     4x   5x 3x 3x         2x   5x                           2x                         3x 1x   2x 2x                                         2x 1x   1x                                   1x 1x                               2x 2x   2x 2x                           1x                   1x                               5x 2x   3x 3x 2x   3x 3x 3x                                     3x   1x 1x   1x 1x   1x 1x   3x                 1x       27x  
"use strict";
 
const EventEmitter = require("events");
const _ = require("lodash");
const HTTPParser = require("http-parser-js").HTTPParser;
const parsers = require("../parsers");
const Headers = require("./Headers");
const responseType = require("../../engine/responseType");
 
/**
 * Response class implements OData particular response
 *
 * @public
 * @class Response
 */
class Response extends EventEmitter {
  /**
   * Initialize instance of the batch Response class
   *
   * @param {Array} rawResponse particular response content from whole batch mulitpart/mime response (lines are array items)
   *
   * @public
   * @memberof Response
   */
  constructor(rawResponse) {
    let resolveResponse;
    let rejectResponse;
 
    super();
 
    Object.defineProperty(this, "promise", {
      value: new Promise(function (resolve, reject) {
        resolveResponse = resolve;
        rejectResponse = reject;
      }),
      writable: false,
    });
 
    Object.defineProperty(this, "resolve", {
      value: resolveResponse,
      writable: false,
    });
 
    Object.defineProperty(this, "reject", {
      value: rejectResponse,
      writable: false,
    });
 
    this.process(rawResponse);
  }
 
  /**
   * Parse and resolve/reject Response.promise
   *
   * @param {Array} rawResponse particular response content from whole batch mulitpart/mime response (lines are array items)
   *
   * @returns {Object} initialized parser (for testing usage)
   *
   * @private
   * @memberof Response
   */
  process(rawResponse) {
    this.body = null;
    _.each(
      this.parseDivideResponse(rawResponse),
      (responseRawValue, responseRawKey) => {
        this[responseRawKey] = responseRawValue;
      }
    );
    let parser = new HTTPParser(HTTPParser.RESPONSE);
    let error;
 
    try {
      parser.onHeadersComplete = this.handlerHeadersComplete.bind(this);
      parser.onBody = this.handlerBody.bind(this);
      parser.onMessageComplete = this.handlerMessageComplete.bind(this);
      parser.execute(
        Buffer.from(
          _.chain(this.rawHTTPResponse)
            .filter((header) => !header.match(/content-length/i))
            .join("\n")
            .value(),
          "binary"
        )
      );
      parser.finish();
      if (parser.state === "HEADER") {
        this.processHeaderInfo(parser.info);
        this.finishProcessResponse(parser.info.statusCode);
      }
    } catch (ex) {
      error = new Error("Unexpected error thrown for response parsing.");
      error.response = this;
      this.reject(error);
    }
 
    return parser;
  }
 
  /**
   * Divide rawResponse to part for MIME content and part of HTTP content
   *
   * @param {Array} rawResponse particular response content from whole batch mulitpart/mime response (lines are array items)
   *
   * @returns {Object} object with "rawHTTPResponse" key and "rawMIMEHeaders" key
   *
   * @private
   * @memberof Response
   */
  parseDivideResponse(rawResponse) {
    let blocks = _.reduce(
      rawResponse,
      (acc, row) => {
        if (row === "") {
          acc.push([]);
        } else {
          acc[acc.length - 1].push(row);
        }
        return acc;
      },
      [[]]
    );
 
    return {
      rawHTTPResponse: _.concat(blocks[1], "", blocks[2]),
      rawMIMEHeaders: blocks[0],
    };
  }
 
  /**
   * Just for compatibility with NodeJS HTTP.Response object
   *
   * @private
   * @memberof Response
   */
  setEncoding() {}
 
  /**
   * Divide rawResponse to part for MIME content and part of HTTP content
   *
   * @returns {String} content type of the particular batch HTTP response
   *
   * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
   *
   * @private
   * @memberof Response
   */
  getContentType() {
    let mediaTypeEnd;
    let contentType = _.find(
      this.headers,
      (headerValue, headerName) =>
        _.isString(headerName) && headerName.toLowerCase() === "content-type"
    );
    if (_.isString(contentType)) {
      mediaTypeEnd = contentType.indexOf(";");
      contentType = contentType.substring(
        0,
        mediaTypeEnd < 0 ? contentType.length : mediaTypeEnd
      );
    } else {
      contentType = null;
    }
    return contentType;
  }
 
  /**
   * Determine parser for the current response
   *
   * @returns {Function} function which is compatible with superagent parser
   *
   * @see http://visionmedia.github.io/superagent/#parsing-response-bodies
   *
   * @private
   * @memberof Response
   */
  getBodyParser() {
    return parsers[this.getContentType()];
  }
 
  /**
   * Handler which is called after the body parsing is done
   *
   * @param {Error} err is error object raised during body parsing
   * @param {Any} content parsed content
   *
   * @private
   * @memberof Response
   */
  handlerParserFinished(err, content) {
    if (err) {
      this.resolve(err);
    } else {
      this.body = content;
      this.finishProcessResponse(
        this.statusCode,
        JSON.stringify(content, null, 2)
      );
    }
  }
 
  /**
   * Helper function which sets correct parser after the headers are
   * loaded and parsed
   *
   * Use by handlerHeadersComplete method
   *
   * @param {Function} bodyParser is function function which is compatible with superagent parser
   *
   * @see http://visionmedia.github.io/superagent/#parsing-response-bodies
   *
   * @private
   * @memberof Response
   */
  useBodyParser(bodyParser) {
    if (bodyParser) {
      bodyParser(this, this.handlerParserFinished.bind(this));
    } else {
      this.on("end", this.handlerParserFinished.bind(this));
    }
  }
 
  /**
   * Handler called when headers are received. Parse headers and set correct body
   * parser.
   *
   * @param {Object} headersInfo object with "headers" key which contains array
   *        of headers. The headers are set as rawHeaders to the Response object
   *        parsed headers are accessible as headers object
   *
   * @see http://visionmedia.github.io/superagent/#parsing-response-bodies
   *
   * @private
   * @memberof Response
   */
  handlerHeadersComplete(headersInfo) {
    this.processHeaderInfo(headersInfo);
    this.useBodyParser(this.getBodyParser());
  }
 
  /**
   * Append parsed headers to the batch response instance
   *
   * @param {Object} headersInfo object with "headers" key which contains array
   *        of headers. The headers are set as rawHeaders to the Response object
   *        parsed headers are accessible as headers object
   *
   * @see http://visionmedia.github.io/superagent/#parsing-response-bodies
   *
   * @private
   * @memberof Response
   */
  processHeaderInfo(headersInfo) {
    _.each(headersInfo, (headerInfoValue, headerInfoKey) => {
      this[headerInfoKey] = headerInfoValue;
    });
    this.rawHeaders = this.headers;
    this.headers = new Headers(this.rawHeaders);
  }
 
  /**
   * Fire event "data" after the new data are recevied
   *
   * @param {Buffer} data buffet with body of the HTTP response
   * @param {Number} offset offset of currently received data
   * @param {Number} len length of currently received data
   *
   * @private
   * @memberof Response
   */
  handlerBody(data, offset, len) {
    this.emit("data", data.toString("binary", offset, offset + len));
  }
 
  /**
   * Fire event "end" when response is fully received and parsed
   *
   * @private
   * @memberof Response
   */
  handlerMessageComplete() {
    this.emit("end");
  }
 
  /**
   * Finish response processing
   *
   * @param {Number} statusCode HTTP status code from raw response
   * @param {String} errorMessage response
   *
   * @private
   * @memberof Response
   */
  finishProcessResponse(statusCode, errorMessage) {
    let message;
    let error;
 
    if (statusCode < 400) {
      this.resolve(this);
    } else {
      message = `${statusCode} - Invalid response inside Batch.`;
      if (_.isString(errorMessage)) {
        message += `\n${errorMessage}`;
      }
      error = new Error(message);
      error.response = this;
      this.resolve(error);
    }
  }
 
  /**
   * Read plain OData response as javascript object from
   * Batch response
   *
   * @public
   *
   * @param {String} listResultPath path to list result (depends on OData version)
   * @param {String} instanceResultPath path to entity result (depends on OData version)
   *
   * @returns {Array|Object} parsed list or entity
   *
   * @memberof agent/batch/Response
   */
  plain(listResultPath, instanceResultPath) {
    let result;
    switch (this.request.responseType) {
      case responseType.COUNT:
        result = parsers.count(_.get(this, "body"));
        break;
      case responseType.LIST:
        result = _.get(this, `body.${listResultPath}`);
        break;
      case responseType.ENTITY:
        result = _.get(this, `body.${instanceResultPath}`, null);
        break;
    }
    return result || this;
  }
 
  /**
   * It is mimicry for Fetch API Response json method
   *
   * @returns {Promise} promise resolved by body as json format
   */
  json() {
    return Promise.resolve(this.body);
  }
}
 
module.exports = Response;