EN
TypeScript - own url builder
6 points
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:
xxxxxxxxxx
1
class UrlBuilder {
2
private cache: string | null = null;
3
private parameters: Record<string, string> = {};
4
5
public constructor(private prefix: string) {
6
// nothing here ...
7
}
8
9
public getParameter = (name: string, defaultValue: string): string => {
10
return this.parameters[name] ?? defaultValue;
11
};
12
13
public setParameter = (name: string, value: string | null): void => {
14
const parameter = this.parameters[name];
15
if (parameter == value) {
16
return;
17
}
18
this.cache = null;
19
if (value == null) {
20
delete this.parameters[name];
21
} else {
22
this.parameters[name] = String(value);
23
}
24
};
25
26
public toString = (): string => {
27
if (this.cache == null) {
28
let url = '';
29
const entries = Object.entries(this.parameters);
30
for (const entry of entries) {
31
const name = encodeURIComponent(entry[0]);
32
const value = encodeURIComponent(entry[1]);
33
url += (url ? '&' : '?') + name + '=' + value;
34
}
35
this.cache = this.prefix + url;
36
}
37
return this.cache;
38
};
39
}
40
41
// Usage example:
42
43
const builder = new UrlBuilder('https://domain.com/page');
44
45
builder.setParameter('preview', true);
46
builder.setParameter('user', 'john');
47
builder.setParameter('age', 20);
48
49
console.log(builder.toString()); // https://domain.com/page?preview=true&user=john&age=20
50
51
builder.setParameter('preview', null);
52
builder.setParameter('user', null);
53
54
console.log(builder.toString()); // https://domain.com/page?age=20