Last active
July 9, 2016 11:30
-
-
Save vjrngn/dd90e40d9c224f9eedc3b3f0be99f716 to your computer and use it in GitHub Desktop.
Http url builder for creating get request params.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function HttpUrlBuilder(url) { | |
if (typeof url !== "string") { | |
throw new TypeError(); | |
} | |
this.url = url; | |
this.cleanUrl(); | |
} | |
HttpUrlBuilder.prototype.cleanUrl = function() { | |
var endOfUrl = this.url.match(/\/$/g); | |
if (endOfUrl === null) { | |
this.url += "?"; | |
return this; | |
} | |
this.url = this.url.replace(/\/$/g, "?"); | |
return this; | |
}; | |
HttpUrlBuilder.prototype.build = function(data) { | |
var params = data || {}, | |
$this = this; | |
Object.keys(params).map(function(key, index) { | |
if (index === 0) { | |
$this.url += key + '=' + encodeURI(params[key]); | |
} else { | |
$this.url += '&' + key + '=' + encodeURI(params[key]); | |
} | |
}); | |
return this.url; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment