...

/

Builder Pattern: Implementing a URL Object Builder

Builder Pattern: Implementing a URL Object Builder

Learn the implementation details of a URL object builder.

We'll cover the following...

We want to implement a Url class that can hold all the components of a standard URL, validate them, and format them back into a string. This class is going to be intentionally simple and minimal, so for standard production use, we recommend the built-in URL class.

Implementation

Now, let’s implement our custom Url class in a url.js named file.

Press + to interact
export class Url {
constructor (protocol, username, password, hostname,
port, pathname, search, hash) {
this.protocol = protocol
this.username = username
this.password = password
this.hostname = hostname
this.port = port
this.pathname = pathname
this.search = search
this.hash = hash
this.validate()
}
validate () {
if (!this.protocol || !this.hostname) {
throw new Error('Must specify at least a ' +
'protocol and a hostname')
}
}
toString () {
let url = ''
url += `${this.protocol}://`
if (this.username && this.password) {
url += `${this.username}:${this.password}@`
}
url += this.hostname
if (this.port) {
url += this.port
}
if (this.pathname) {
url += this.pathname
}
if (this.search) {
url += `?${this.search}`
}
if (this.hash) {
url += `#${this.hash}`
}
return url
}
}

A standard URL is made of several components, so to take them all in, the Url class’ constructor is inevitably big. Invoking such a constructor can be a challenge, as we have to keep track of the argument position to know what component of the URL we’re passing. Take a look at the following example to get an idea of ...