All files / lib/engine/entitySet Sorter.js

100% Statements 12/12
100% Branches 4/4
100% Functions 7/7
100% Lines 12/12

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    1x                             12x         12x                       11x 19x   26x   19x   18x 17x 1x                           8x       1x  
"use strict";
 
const _ = require("lodash");
 
/**
 * Class to implement sort handling for OData library client.
 *
 * @class Sorter
 */
class Sorter {
  /**
   * Creates an instance of Sorter.
   * @param {Object} entityType information about EntityType parsed from Metadata
   * @param {string} parts parts of the orderby clause
   * @memberof Sorter
   */
  constructor(entityType, parts) {
    Object.defineProperty(this, "parts", {
      value: parts,
      writable: false,
    });
 
    this.validate(entityType, parts);
  }
 
  /**
   * Validates the input
   *
   * Checks if all properties are Sortable
   *
   * @param {Object} entityType information about EntityType parsed from Metadata
   * @param {string} parts parts of the orderby clause
   */
  validate(entityType, parts) {
    _.chain(parts)
      .reduce((properties, part) => properties.concat(part.split(" ")), [])
      // Filter out asc/desc keywords
      .filter((property) => property !== "asc" && property !== "desc")
      // Filter out nested properties (eg. $orderby=Rating,Category/Name)
      .filter((property) => property.indexOf("/") === -1)
      .forEach((property) => {
        let metaProp = entityType.getProperty(property);
        if (!metaProp.sap.sortable) {
          throw new Error(
            `Property ${property} cannot be used in orderby clause as it is not sortable`
          );
        }
      })
      .value();
  }
 
  /**
   * Convert sorter to the URI Component
   *
   * @returns {String} string which contains sorter with encoded characters
   */
  toURIComponent() {
    return encodeURIComponent(_.chain(this.parts).join(",").value());
  }
}
 
module.exports = Sorter;