lamchau
11/25/2014 - 7:36 AM

fixture pattern matcher

fixture pattern matcher

function parseUrl(url) {
  url = String(url);
  // expects api calls to be "/some/api/v(#)/some/path" with optional query params
  // examples: http://regex101.com/r/vO8mU5/1
  var regex = /.*\/v(\d+)((?:\/\w+)+)\??(.+)?$/i;
  var match = url.match(regex);

  console.assert("Invalid URL '" + url + "'", match);

  var result = {
    "url": url,
    "version": +match[1],
    "endpoint": match[2],
    "params": match[3]
  };

  console.assert("API version '" + result.version + "' must greater than 0", result.version > 0);
  return result;
}