All files / fuse-ui-shared url.ts

92.86% Statements 26/28
59.09% Branches 13/22
100% Functions 9/9
92.31% Lines 24/26
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 651x   1x 1x 1x                         1x     1x 2x 2x 2x 2x 2x   2x           1x               1x 2x       2x 8x         1x 1x 1x   1x   1x     1x 2x    
import * as _ from 'underscore';
 
export enum Scheme {
  http,
  https
}
 
export interface Url {
  scheme: Scheme;
  hostname: string;
  port?: number;
  path: string;
  query: string | { [key: string]: string };
  format(): string;
}
 
// regex to split urls into components
const urlregex = /^(http:\/\/|https:\/\/)([^:\/]+)(:[0-9]+){0,1}(\/[^?]*){0,1}(\?[^#]*){0,1}/;
 
// tslint:disable:no-invalid-this
export function parseUrl(url: string): Url {
  let matches = urlregex.exec(url);
  Eif (matches) {
    const schemestring = matches[1].substr(0, matches[1].length - 3);
    const host = matches[2];
    const port = matches[3];
 
    return {
      scheme: Scheme[schemestring],
      hostname: host,
      port: port ? parseInt(port.substr(1), 10) : undefined,
      path: matches[4],
      query: matches[5] ? parseQuery(matches[5].substr(1)) : undefined,
      format: function () { return formatUrl(this); }
    };
  }
 
  return null;
}
// tslint:enable:no-invalid-this
 
export function parseQuery(query: string): { [key: string]: string } | undefined {
  Iif (!query) {
    return undefined;
  }
 
  return _.object(_.map(query.split('&'), exp => {
    return _.map(exp.split(/=(.+)?/, 2), (v, i) => i === 0 ? v : decodeURIComponent(v));
  }));
}
 
function formatUrl(url: Url): string {
  let querystring = '';
  Eif (url.query) {
    querystring = `?${_.isString(url.query) ? url.query : formatQuery(<any>url.query)}`;
  }
  let schemestring = _.isString(url.scheme) ? url.scheme : Scheme[url.scheme];
 
  return `${schemestring}://${url.hostname}${_.isUndefined(url.port) ? '' : `:${url.port}`}${url.path || ''}${querystring}`;
}
 
export function formatQuery(obj: { [key: string]: any }): string {
  return Object.keys(obj).map(k => `${k}=${encodeURIComponent(obj[k])}`).join('&');
}