All files / route Route.js

86.36% Statements 19/22
78.57% Branches 11/14
100% Functions 6/6
86.36% Lines 19/22

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                            32x       32x 1x     31x       31x       31x 31x 31x 31x       32x                                 15x   15x 18x   13x 13x       15x                   19x 19x                 32x      
import { hasOwn } from '../shared/utils'
 
/**
 * @class Route
 */
export class Route {
  /**
   *
   * @param {String} module
   * @param {String} action
   * @param {String} url
   * @param {Array} parameters
   */
  constructor (module, action, url, parameters) {
    Iif (typeof module !== 'string') {
      throw new Error('Module name must be string')
    }
 
    if (!this.isValidAction(action)) {
      throw new Error('Action must be valid resourceful verb')
    }
 
    Iif (typeof url !== 'string') {
      throw new Error('URL must be string')
    }
 
    Iif (parameters.constructor !== Array) {
      throw new Error('Parameters must be array')
    }
 
    this.module = module
    this.action = action.toLowerCase()
    this.url = url
    this.parameters = parameters
  }
 
  get supportedResourcefulVerbs () {
    return [
      'list',
      'get',
      'create',
      'replace',
      'update',
      'delete'
    ]
  }
 
  /**
   * Prepare an url, replacing provided parameters
   *
   * @param parameters
   * @returns {string}
   */
  prepare (parameters) {
    let url = this.url
 
    for (const param in parameters) {
      if (hasOwn(parameters, param) &&
        this.hasParameter(param)) {
        url = url.replace('{' + param + '}', parameters[param])
        delete parameters[param]
      }
    }
 
    return url
  }
 
  /**
   * Check if a parameter is allowed
   *
   * @param parameter
   * @returns {boolean}
   */
  hasParameter (parameter) {
    return this.parameters.filter((checkParam) => {
      return parameter === checkParam
    }).length > 0
  }
 
  /**
   *
   * @param {String} action
   */
  isValidAction (action) {
    return typeof action === 'string' && this.supportedResourcefulVerbs.indexOf(action.toLowerCase()) > -1
  }
}