cms/app-client/mirage/serializers/utils.js
author ymh <ymh.work@gmail.com>
Fri, 16 Dec 2016 17:43:07 +0100
changeset 474 245b4df137d3
parent 324 92fc9d077f95
child 543 aaaf9b0b09f6
permissions -rw-r--r--
Correct themes visualisation

// taken from http://blog.stevenlevithan.com/archives/parseuri
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
import _ from 'lodash';

const PARSEURI_DEFAULT_OPTIONS = {
  strictMode: false,
  key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  q: {
    name:   "queryKey",
    parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
    loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};

export default {
  parseUri : function (str, options) {
    var o = _.defaultsDeep(options || {}, PARSEURI_DEFAULT_OPTIONS);
    var	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

    while (i--) { uri[o.key[i]] = m[i] || ""; }

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
      if ($1) { uri[o.q.name][$1] = $2; }
    });

    return uri;
  },
  mergeUri : function(uriParts) {
    let res = "";
    if(uriParts.protocol) {
      res += uriParts.protocol+":";
    }
    if(uriParts.host) {
      res += "//" + uriParts.host;
    }
    if(uriParts.port) {
      res += ":" + uriParts.port;
    }
    if(uriParts.path) {
      res += uriParts.path;
    }
    if(uriParts.queryKey) {
      res += "?" + _.map(uriParts.queryKey, function(v,k) {
        return k + "=" + v;
      }).join("&");
    }

    return res;
  }
};