All files / ima/http UrlTransformer.js

100% Statements 14/14
100% Branches 2/2
100% Functions 6/6
100% Lines 13/13
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    4x             6x                   9x                           13x   13x                 3x   3x                       4x   4x 1x     3x   3x       4x  
import ns from '../namespace';
 
ns.namespace('ima.http');
 
/**
 * Utility for transforming URLs according to the configured replacement rules.
 */
export default class UrlTransformer {
  static get $dependencies() {
    return [];
  }
 
  /**
	 * Initializes the URL transformer.
	 */
  constructor() {
    /**
		 * @type {Object<string, string>}
		 */
    this._rules = {};
  }
 
  /**
	 * Adds the provided replacement rule to the rules used by this URL
	 * transformer.
	 *
	 * @param {string} pattern Regexp patter to look for (must be escaped as if
	 *        for use in the {@linkcode Regexp} constructor).
	 * @param {string} replacement The replacement of the matched patter in any
	 *        matched URL.
	 * @return {UrlTransformer} This transformer.
	 */
  addRule(pattern, replacement) {
    this._rules[pattern] = replacement;
 
    return this;
  }
 
  /**
	 * Clears all rules.
	 *
	 * @return {UrlTransformer} This transformer.
	 */
  clear() {
    this._rules = {};
 
    return this;
  }
 
  /**
	 * Applies all rules registered with this URL transformer to the provided
	 * URL and returns the result. The rules will be applied in the order they
	 * were registered.
	 *
	 * @param {string} str The URL for transformation.
	 * @return {string} Transformed URL.
	 */
  transform(str) {
    let rulesKey = Object.keys(this._rules);
 
    if (rulesKey.length === 0) {
      return str;
    }
 
    let reg = new RegExp(rulesKey.join('|'), 'g');
 
    return str.replace(reg, ruleKey => this._rules[ruleKey]);
  }
}
 
ns.ima.http.UrlTransformer = UrlTransformer;