Skip to content

Instantly share code, notes, and snippets.

@sposmen
Forked from cakebaker/gist:823574
Last active August 29, 2015 14:05
Show Gist options
  • Save sposmen/960ab88a062f2848f8ce to your computer and use it in GitHub Desktop.
Save sposmen/960ab88a062f2848f8ce to your computer and use it in GitHub Desktop.
'use strict';
var UrlAdapter = require('./UrlAdapter'),
url = new UrlAdapter('https://www.domain.com/data?param1=1&param2=2&param3=3&param4=4&paramN=N');
url.leaveParams(['param1', 'param3', 'paramN']);
console.log(url.toString());
url = new UrlAdapter('?param1=1&param2=2&param3=3&param4=4&paramN=N');
url.removeParams(['param1', 'param2', 'param6']); //
console.log(url.toString());
'use strict';
var urlLib = require('url');
function UrlAdapter(urlString) {
this.urlObj = urlLib.parse(urlString, true);
// XXX remove the search property to force format() to use the query object when transforming the url object to a string
delete this.urlObj.search;
}
UrlAdapter.prototype.parse = urlLib.parse;
UrlAdapter.prototype.hasQueryString = function () {
return !!this.urlObj.query;
};
UrlAdapter.prototype.removeParam = function (param) {
if (this.hasQueryString()) {
delete this.urlObj.query[param];
}
return this;
};
UrlAdapter.prototype.setParam = function (param, value) {
if (!this.hasQueryString()) {
this.urlObj.query = {};
}
this.urlObj.query[param] = value;
return this;
};
UrlAdapter.prototype.removeParams = function (params) {
for (var i = 0; i < params.length; i++) {
this.removeParam(params[i]);
}
return this;
};
UrlAdapter.prototype.leaveParams = function(params){
var toRemove = Object.keys(this.urlObj.query).
filter( function (paramName) {
return params.indexOf(paramName) === -1;
});
return this.removeParams(toRemove);
};
UrlAdapter.prototype.toString = function () {
return urlLib.format(this.urlObj);
};
module.exports = UrlAdapter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment