All files / lib/agent/batch Base.js

100% Statements 15/15
100% Branches 4/4
100% Functions 5/5
100% Lines 15/15

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    7x 7x                                           103x 1x   102x       102x       102x       102x                                 5x   5x   5x                         103x                       1x 3x         7x  
"use strict";
 
const crypto = require("crypto");
const _ = require("lodash");
 
/**
 * Base class for batch classes which implements list of other batch objects
 * (batches, changsets, requests)
 *
 * @private
 * @class Base
 */
class Base {
  /**
   * Call the method by the <code>super</code>
   *
   * @param {String} listName is the name of the property in the
   *        descendant class which is use as list of batch objects
   * @param {String} boundaryPrefix the boundary prefix for the
   * 		  multipart content of the batch request
   *
   * @public
   * @memberof Base
   */
  constructor(listName, boundaryPrefix) {
    if (!_.isString(listName)) {
      throw new Error("Invalid definition of the main list of batch objects");
    }
    Object.defineProperty(this, "listName", {
      value: listName,
      writable: false,
    });
    Object.defineProperty(this, "boundaryPrefix", {
      value: boundaryPrefix || "",
      writable: false,
    });
    Object.defineProperty(this, "id", {
      value: this.generateId(),
      writable: false,
    });
    Object.defineProperty(this, listName, {
      value: [],
      writable: false,
    });
  }
 
  /**
   * Add new item to the batch list object
   *
   * @param {Class} BatchObject class definition for newly created object
   *
   * @returns {Object} create instance of the BatchObject class
   *
   * @private
   * @memberof Base
   */
  add(BatchObject, ...args) {
    let batchObject = new BatchObject(...args);
 
    this[this.listName].push(batchObject);
 
    return batchObject;
  }
 
  /**
   * Generate id for the batch object (for batches and changests) which
   * identifies the batch object
   *
   * @returns {String} returns string with 12 hexadecimal numbers
   *
   * @private
   * @memberof Base
   */
  generateId() {
    return crypto.randomBytes(6).toString("hex");
  }
 
  /**
   * Generate batch boundary for the multipart/mixed content
   *
   * @returns {String} boundary used by the batch response
   *
   * @private
   * @memberof Batch
   */
  boundary() {
    return `${this.boundaryPrefix}_${_.map([0, 1, 2], (index) =>
      this.id.substring(index * 4, (index + 1) * 4)
    ).join("-")}`;
  }
}
 
module.exports = Base;