Languages
[Edit]
EN

TypeScript - own url builder

6 points
Created by:
Mahir-Bright
1101

In this short article, we would like to show how to create a custom URL builder in TypeScript.

It is problematic when we make some operations on URLs that each time force us to write some code that encodes and combines parameters together - the solution is to use URL class or write own simple custom class what was presented in the below example.

Note: to see JavaScript version go to this article.

Warning: below source code uses Object.entries() function that was introduced in ES2017 - do not forget to polyfill source code.

Practical example:

class UrlBuilder {
	private cache: string | null = null;
	private parameters: Record<string, string> = {};

	public constructor(private prefix: string) {
		// nothing here ...
	}

	public getParameter = (name: string, defaultValue: string): string => {
		return this.parameters[name] ?? defaultValue;
	};

	public setParameter = (name: string, value: string | null): void => {
		const parameter = this.parameters[name];
		if (parameter == value) {
			return;
        }
		this.cache = null;
		if (value == null) {
			delete this.parameters[name];
        } else {
			this.parameters[name] = String(value);
        }
	};

	public toString = (): string => {
		if (this.cache == null) {
			let url = '';
			const entries = Object.entries(this.parameters);
			for (const entry of entries) {
				const name = encodeURIComponent(entry[0]);
				const value = encodeURIComponent(entry[1]);
				url += (url ? '&' : '?') + name + '=' + value;
			}
			this.cache = this.prefix + url;
		}
		return this.cache;
	};
}
  
// Usage example:
  
const builder = new UrlBuilder('https://domain.com/page');
  
builder.setParameter('preview', true);
builder.setParameter('user', 'john');
builder.setParameter('age', 20);

console.log(builder.toString()); // https://domain.com/page?preview=true&user=john&age=20

builder.setParameter('preview', null);
builder.setParameter('user', null);
  
console.log(builder.toString()); // https://domain.com/page?age=20

See also

  1. JavaScript - own url builder 

Alternative titles

  1. TypeScript - custom url builder
  2. TypeScript - custom simple url builder
  3. TypeScript - own simple url builder
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join