You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.3 KiB
JavaScript

"use strict";
const url = require("url");
module.exports = function modifyUrl(baseUrl, newProps_, options = {}) {
if (baseUrl == null) {
throw new Error("Must specify a base URL");
} else if (newProps_ == null) {
throw new Error("Must specify new properties");
} else if (typeof baseUrl !== "string") {
throw new Error("Base URL must be a string");
} else if (typeof newProps_ !== "object" || Array.isArray(newProps_)) {
throw new Error("New properties must be an object");
} else if (options.mergeQuery === true && newProps_.search != null) {
throw new Error("You can only use `query`, not `search`, when the `mergeQuery` option is enabled");
} else {
let parsedBaseUrl = url.parse(baseUrl, true);
let newProps = Object.assign({}, newProps_);
if (newProps.query != null) {
parsedBaseUrl.search = null;
}
if (newProps.hostname != null || newProps.port != null) {
parsedBaseUrl.host = null;
}
let newQuery;
if (newProps.query != null) {
if (options.mergeQuery === true) {
newQuery = Object.assign(parsedBaseUrl.query, newProps.query)
} else {
newQuery = newProps.query;
}
} else {
newQuery = parsedBaseUrl.query;
}
return url.format(Object.assign({}, parsedBaseUrl, newProps, {
query: newQuery
}));
}
};