Skip to content

Instantly share code, notes, and snippets.

@zinthose
Created December 26, 2021 23:02
Show Gist options
  • Save zinthose/e80de76119019b801186959774f79cd7 to your computer and use it in GitHub Desktop.
Save zinthose/e80de76119019b801186959774f79cd7 to your computer and use it in GitHub Desktop.
Simple function to build a URL with URI parameters. Function allows for default values and a mechanism to require parameters.
/**
* Simple object that requires each keyed value to be a string.
*/
interface StringObject {[key: string]: string;}
/**
* Utility function to create a URL with parameters.
* @param url Base URL to build for.
* @param uri_values URI parameters to encode add to URL
* @param default_values Default URI parameters to encode into URL. Use this to define defaults to add.
* @param required_keys String array of all the parameter keys that are required.
* @returns Final URL combining URL and URI
*
* Example:
* ```typescript
* var url = _buildURL(
* "https://www.google.com", // Set Base URL
* {"q": "Who is best Pony?"}, // Set Supplied Search Value
* {"q": "What is this TypeScript stuff?"}, // Set Default Search Value
* ["q"] // Set Required parameters
* );
* ```
*/
function _buildURL(url:string, uri_values: StringObject = {}, default_values: StringObject = {}, required_keys: Array<string> = []) {
// Merge Default Values with supplied values
const merged_uri = {...default_values, ...uri_values};
// Check to ensure all required keys are set
const hasAllKeys = required_keys.every(key => {
const has_key = merged_uri.hasOwnProperty(key);
if (!has_key) throw `${_buildURL.name}}: Required key "${key}" was not set.`;
return has_key;
});
// Build URI and return final URL
const uri = new URLSearchParams(merged_uri).toString();
if (uri === "") return url;
return url + "?" + uri;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment