mwoffliner
Version:
MediaWiki ZIM scraper
68 lines • 2.37 kB
JavaScript
import { ensureTrailingChar } from '../../misc.js';
/**
* Concat the path to the domain and setting query params
*/
class URLBuilder {
domain = '';
path = '';
queryParams = '';
setDomain(domain) {
this.domain = domain;
return this;
}
setPath(path) {
this.path = path;
return this;
}
/**
* This function sets query parameters for a URL.
*
* @param params - These key-value pairs represent the query parameters that will be added to the URL.
* @param [trailingChar] - trailingChar is an optional parameter that specifies a character
* to be added at the beginning of the query parameters string. It is used to indicate the start of
* the query parameters in a URL.
*
* @returns the current object (`this`) after setting the `queryParams` property to a string
*/
setQueryParams(params, trailingChar = '?', filterParams) {
if (!filterParams) {
const queryParams = new URLSearchParams(params);
this.queryParams = trailingChar + queryParams.toString();
return this;
}
const filteredParams = Object.keys(params).reduce((accum, key) => {
if (params[key]) {
accum[key] = params[key];
}
return accum;
}, {});
const queryParams = new URLSearchParams(filteredParams);
this.queryParams = trailingChar + queryParams.toString();
return this;
}
build(returnUrl, trailingChar) {
const currentDomain = this.domain;
const currentPath = this.path;
const currentQueryParams = this.queryParams;
this.domain = '';
this.path = '';
this.queryParams = '';
if (!currentDomain) {
throw new Error('The link must contain a domain');
}
const link = currentDomain + currentPath + currentQueryParams;
if (returnUrl && trailingChar) {
return new URL(ensureTrailingChar(link, trailingChar));
}
if (returnUrl && !trailingChar) {
return new URL(link);
}
if (!returnUrl && trailingChar) {
return ensureTrailingChar(link, trailingChar);
}
return link;
}
}
const urlBuilder = new URLBuilder();
export default urlBuilder;
//# sourceMappingURL=url.builder.js.map