All files / lib/engine RequestDefinition.js

100% Statements 132/132
100% Branches 67/67
100% Functions 36/36
100% Lines 131/131

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 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 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596    39x 39x 39x 39x 39x 39x                   3x 1x                       6x 6x 1x 5x 1x   4x     6x                               123x       123x                     2x 1x         1x 1x   1x                                 6x 3x         3x 3x                         9x                           2x 2x                         6x 3x   3x 2x 2x       2x   3x     2x                           4x 1x           3x 3x   3x                     4x 4x     4x                       7x 7x                 3x 3x 2x   2x       2x 1x   1x           3x   3x                           4x 3x 2x   1x         1x         2x                                           10x 9x   10x     9x 12x     1x     5x         5x                               3x                                       3x                                                 10x 9x   10x     9x 12x 9x 11x     11x             1x     5x   5x                                     12x 11x       1x     11x                             6x 1x         5x   5x 2x         3x   3x                         4x 3x 2x   1x     1x         2x                     5x   5x 4x   1x                         10x           14x 14x                             1x 1x                     8x 8x 4x       4x 4x   4x 4x     4x       4x 1x 1x 1x 1x     4x     4x 3x   1x                                     2x 2x 1x   2x       39x  
"use strict";
 
const _ = require("lodash");
const urlUtils = require("../agent/url");
const Filter = require("./entitySet/Filter");
const Sorter = require("./entitySet/Sorter");
const responseType = require("./responseType");
const requestPath = require("./request/path");
 
/**
 * Check validity of the key property
 *
 * @param {Object} keyDef definiton of key from metadata
 * @param {Any} entityValue value which is passed to the key
 *
 */
function checkKeyProperty(keyDef, entityValue) {
  if (!keyDef.nullable && (entityValue === undefined || entityValue === null)) {
    throw new Error(`Key property ${keyDef.name} is not defined.`);
  }
}
 
/**
 * Applies optional argument (top/key)
 *
 * @param {RequestDefinition} request to modify
 * @param {*} args arguments to validate and apply
 * @returns {bool} true if arguments are valid or empty
 */
function applyOptionalArgument(request, args) {
  let ok = true;
  if (args.length === 1 && _.isNumber(args[0])) {
    request.top(args[0]);
  } else if (args.length === 1 && _.isPlainObject(args[0])) {
    request.key(args[0]);
  } else {
    ok = args.length === 0;
  }
 
  return ok;
}
 
/**
 * Envelope OData request
 *
 * @class RequestDefinition
 */
class RequestDefinition {
  /**
   * Creates an instance of RequestDefinition.
   * @param {*} resource owning resource
   * @param {*} defaults initial query values
   * @memberof RequestDefinition
   */
  constructor(resource, defaults) {
    Object.defineProperty(this, "_resource", {
      value: resource,
    });
 
    _.merge(this, defaults);
  }
 
  /**
   * Send request to count of the EntitySet
   *
   * @return {Promise} returned promise is resolved when request is finished
   *
   * @memberof QueryableResource
   */
  count() {
    if (!this._resource.entitySetModel.sap.countable) {
      throw new Error(
        `The EntitySet ${this._resource.entitySetModel.name} is not countable.`
      );
    }
 
    this._isCount = true;
    this.calculatePath();
 
    return this._resource.executeGet(this);
  }
 
  /**
   * Sends GET request to the entity set.
   *
   * @param {*} args some arguments
   * supported argument variants
   * 1. no arguments and key not defined -> list query
   * 2. no arguments and key defined -> get entity entity
   * 3. one plain object argument -> get entity with key from this object
   * 4. one number argument -> list top query
   *
   * @return {Promise} returned promise is resolved when request is finished
   * @memberof QueryableResource
   */
  get(...args) {
    if (!applyOptionalArgument(this, args)) {
      throw new Error(
        "Read content by the combination of parameters is not implemented."
      );
    }
 
    this.calculatePath();
    return this._resource.executeGet(this);
  }
 
  /**
   * Get query parameter from the entity set query structure.
   *
   * @param {String} name name of the parameter
   *
   * @return {String} current value of the query parameter
   *
   * @memberof Resource
   */
  getQueryParameter(name) {
    return _.get(this._query, name);
  }
 
  /**
   * Set additional header for the OData request to the resource
   *
   * @param {String} key name of the header
   * @param {String} value value of the header
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  header(key, value) {
    this._headers[key] = value;
    return this;
  }
 
  /**
   * Set key definiton for the entity set reading
   *
   * @param {Object} entityKey plain object with definition of the key
   *
   * @return {EntitySet} itself for the chaining
   *
   * @memberof QueryableResource
   */
  key(entityKey) {
    if (_.isPlainObject(entityKey)) {
      this._keyValue = this._resource.entityTypeModel.key.reduce(
        (acc, keyDef) => {
          checkKeyProperty(keyDef, entityKey[keyDef.name]);
          acc[keyDef.name] = entityKey[keyDef.name];
          return acc;
        },
        {}
      );
      this.registerAssociations();
    } else {
      throw new Error("Entity key is not plain object.");
    }
 
    return this;
  }
 
  /**
   * Add parameter to the current request
   *
   * @param {String} parameterName is name of the parameter
   * @param {*} parameterValue is value passed as parameter
   *
   * @returns {RequestDefinition} itself for chaining
   *
   * @memberof RequestDefinition
   */
  parameter(parameterName, parameterValue) {
    if (!this._resource.getParameterDefinition) {
      throw new Error(
        `Resource ${this._resource.name} doesn't support parameters.`
      );
    }
 
    let parameterDefinition =
      this._resource.getParameterDefinition(parameterName);
    this._parameters[parameterName] =
      parameterDefinition.type.format(parameterValue);
    return this;
  }
 
  /**
   * Add parameters to the current request
   *
   * @param {Object} [parameters] is object which contains key/values for parameters
   * @returns {RequestDefinition} itself for chaining
   * @memberof RequestDefinition
   */
  parameters(parameters) {
    if (_.isPlainObject(parameters)) {
      _.each(parameters, (value, key) => this.parameter(key, value));
    }
 
    return this;
  }
 
  /**
   * After the call of the method the superagent response is resolved instead
   * of the plain objects
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  raw() {
    this._isRaw = true;
    return this;
  }
 
  /**
   * Creates Object with OData Associations wrappers
   * @returns {RequestDefinition} itself for the chaining
   * @memberof RequestDefinition
   */
  registerAssociations() {
    this.navigationProperties = {};
    this._resource.entityTypeModel.navigationProperties.forEach((property) => {
      let name = property.name;
 
      this.navigationProperties[name] = this._resource.createNavigationProperty(
        this._resource.metadata,
        property
      );
      if (!this[name]) {
        this[name] = this.navigationProperties[name];
      } else {
        this._resource.agent.logger.warn(
          `Association ${name} is not accessible as shorthand.`
        );
      }
    });
 
    this.populateActions(this._resource.entitySetModel.actions);
 
    return this;
  }
 
  /**
   * Search parameter is SAP enhancement for fulltext search
   * in the EntitySet values
   *
   * @param {String} pattern string which is used as pattern for the fulltext searcb
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  search(pattern) {
    if (this._resource.entitySetModel.sap.searchable) {
      if (_.isString(pattern)) {
        this.setQueryParameter("search", pattern);
      } else {
        throw new Error(
          `The  pattern ${pattern} is not correct patter for search.`
        );
      }
    } else {
      throw new Error(
        `The EntitySet ${this._resource.entitySetModel.name} is not searcheable.`
      );
    }
 
    return this;
  }
 
  /**
   * Limit properties which is fetched from OData server
   *
   * @param {String|[String]} propertyName name of the property which is selected
   *        You can pass more parameterNames at once also:
   *
   * @example
   *        service.EntitySetName.select("Property_Name_1", "Property_Name_1");
   *        service.EntitySetName.select(["Property_Name_1", "Property_Name_1"]);
   *
   * @see
   *        https://www.odata.org/getting-started/basic-tutorial/#select
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  select() {
    let propertyNames;
    if (arguments.length > 0) {
      propertyNames = _.reduce(
        arguments,
        (acc, property) => _.concat(acc, property),
        []
      );
      propertyNames.forEach((name) =>
        this._resource.entityTypeModel.getProperty(name)
      );
    } else {
      throw new Error("Missing parameter.");
    }
 
    this.setQueryParameter(
      "$select",
      propertyNames.map(encodeURIComponent).join(",")
    );
 
    return this;
  }
 
  /**
   * Sets filter for entity list query.
   *
   * @param {String} filter filter expression
   *
   * @example
   * 		service.EntitySetName.orderby("Property_1 eq 'x'");
   *
   * @returns {RequestDefinition} itself to allow method chaining
   *
   * @memberof RequestDefinition
   */
  filter(filter) {
    return this.setQueryParameter(
      "$filter",
      new Filter(filter).toURIComponent()
    );
  }
 
  /**
   * Sets sort order for entity list query.
   *
   * @param {String|[String]} args property sort expression(s), asc is default sort direction
   *
   * @example
   * 		service.EntitySetName.orderby("Property_1");
   * 		service.EntitySetName.orderby("Property_1", "Property_2 desc");
   *
   * @returns {RequestDefinition} itself to allow method chaining
   *
   * @memberof RequestDefinition
   */
  orderby(...args) {
    return this.setQueryParameter(
      "$orderby",
      new Sorter(this._resource.entityTypeModel, args).toURIComponent()
    );
  }
 
  /**
   * Specifies the related resources to be included in line with retrieved resources.
   *
   * @param {String|[String]} path path to resource to be expanded
   *        You can pass more parameterNames at once also:
   *
   * @example
   *        service.EntitySetName.expand("Property_1", "Property_2/Property_3");
   *        service.EntitySetName.expand(["Property_1", "Property_2/Property_3"]);
   *
   * @see
   *        https://www.odata.org/getting-started/basic-tutorial/#expand
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  expand() {
    let paths;
    if (arguments.length > 0) {
      paths = _.reduce(
        arguments,
        (acc, property) => _.concat(acc, property),
        []
      );
      paths.forEach((expandPath) => {
        let navigationProperties = expandPath.split("/");
        navigationProperties.reduce((acc, navigationPropertyName) => {
          let navigationProperty = acc.getNavigationProperty(
            navigationPropertyName
          );
          return navigationProperty.getTarget(
            this._resource.metadata.model.getSchema(),
            this._resource.entitySetModel
          ).entityType;
        }, this._resource.entityTypeModel);
      });
    } else {
      throw new Error("Missing parameter.");
    }
 
    this.setQueryParameter("$expand", paths.map(encodeURIComponent).join(","));
 
    return this;
  }
 
  /**
   * Set query parameter to the get entity set list request
   * You can use the function instead of the specific methods
   * like search or top, but you have to follow the OData protocol.
   * @see https://www.odata.org/getting-started/basic-tutorial/
   * Particular function like top or search contains additionals
   * value checks, but queryParameter just pass value to the
   *
   * @param {String} name name of the parameter
   * @param {Any} [value] parameter value is optional, if it is
   *
   * @return {RequestDefinition} himself for the chaining
   *
   * @memberof RequestDefinition
   */
  setQueryParameter(name, value) {
    if (value === undefined || value === null || !_.isFunction(value)) {
      this._query = _.assign(this._query, {
        [name]: value,
      });
    } else {
      throw new Error("Try to pass invalid value to query parameter.");
    }
 
    return this;
  }
 
  /**
   * Set offset which is used read the entities
   *
   * @param {Number} skip is number of entities which to be skipped
   *
   * @return {EntitySet} itself for the chaining
   *
   * @memberof QueryableResource
   */
  skip(skip) {
    let skipNormalized;
 
    if (this._resource.entitySetModel.sap.pageable !== true) {
      throw new Error(
        `You can't use skip clause. The EntitySet ${this._resource.entitySetModel.name} is not pageable.`
      );
    }
 
    skipNormalized = parseInt(skip, 10);
 
    if (isNaN(skipNormalized) || skipNormalized < 0) {
      throw new Error(
        `Invalid skip value: "${skip}". Skip has to be positive integer.`
      );
    }
 
    this.setQueryParameter("$skip", skip);
 
    return this;
  }
 
  /**
   * Limit number of values which is returned from the service
   *
   * @param {Number} top is number of records which could to be returned
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  top(top) {
    if (this._resource.entitySetModel.sap.pageable) {
      if (_.isNumber(top)) {
        this.setQueryParameter("$top", top);
      } else {
        throw new Error(`Invalid top value: "${top}". Top has to be number.`);
      }
    } else {
      throw new Error(
        `The EntitySet ${this._resource.entitySetModel.name} is not pageable.`
      );
    }
 
    return this;
  }
 
  /**
   * Caculate path for GET request.
   *
   * @private
   *
   * @memberof RequestDefinition
   */
  calculatePath() {
    const foundResponseType = responseType.determine(this, this._resource);
 
    if (foundResponseType && _.has(requestPath.calculate, foundResponseType)) {
      this._path = requestPath.calculate[foundResponseType](this);
    } else {
      this._path = requestPath.default(this);
    }
  }
 
  /**
   * Determines if GET target is list.
   *
   * @returns {bool} true if target can contain multiple values
   *
   * @private
   * @memberof RequestDefinition
   */
  get _isList() {
    return this._resource.isParameterized || !this._isEntity;
  }
 
  get _isEntity() {
    // Navigation property: If the multiplicity is 1..1 then no key is required and there will always be a single entity result
    let isNavPropSingle =
      _.isFunction(this._resource.isMultiple) && !this._resource.isMultiple();
    return (
      _.has(this, "_keyValue") || _.has(this, "_payload") || isNavPropSingle
    );
  }
 
  /**
   * Set payload definiton for the entity set create/update operations
   *
   * @param {Object} payload plain object with definition payload
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  payload(payload) {
    this._payload = payload;
    return this;
  }
 
  /**
   * Populate actions to the service object
   *
   * @param {model.oasis.schema.Action[]} actions array of action defintions
   *
   * @memberof RequestDefinition
   */
  populateActions(actions) {
    this.actions = {};
    _.each(actions, (action) => {
      let schemaAlias = _.get(
        this._resource.metadata.model.getSchema(),
        "alias"
      );
      let name = action.name;
      let fullName = schemaAlias ? `${schemaAlias}.${name}` : name;
 
      this.actions[name] = function (parameters) {
        let urlQuery = this._resource.urlQuery({
          $format: "json",
        });
        this._path = urlUtils.absolutizePath(
          `${this._resource.getSingleResourcePath()}/${fullName}?${urlQuery}`
        );
 
        if (parameters) {
          this._parameters = {};
          this.parameters(parameters);
          this._payload = this._parameters;
          this.header("Content-type", "application/json");
        }
 
        return this._resource.callAction(this);
      }.bind(this);
 
      if (!this[name]) {
        this[name] = this.actions[name];
      } else {
        this._resource.agent.logger.warn(
          `Actions ${name} is not accessible as shorthand.`
        );
      }
    });
  }
 
  /**
   * Mark request definition as request for raw value ($value keyword)
   *
   * @param {String} [propertyName] name of property which is asked (if
   *        parameter is not set $value keyword will be use for whole
   *        entity}
   *
   * @return {RequestDefinition} itself for the chaining
   *
   * @memberof RequestDefinition
   */
  value(propertyName) {
    this._isValue = true;
    if (arguments.length > 0) {
      this._valuePropertyName = propertyName;
    }
    return this._resource;
  }
}
 
module.exports = RequestDefinition;